## DEV Community is a community of 756,528 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Andrew βοΈ & β

Posted on

# Count of positives / sum of negatives with JavaScript

To solve this problem, we'll take 3 different approaches.
Enjoy the video ππ

Also written version https://losseff.xyz/katas/016-count-of-positives-sum-of-negatives/javascript/

## Discussion (2)

Alfredo Salzillo πΊ • Edited on

With only a reduce:

``````function countPositivesSumNegatives(input) {
return input?.reduce(([pSum, nSum], curr) => [pSum + Math.max(0, Math.sign(curr)), nSum + Math.min(0, curr)], [0, 0]) || [];
}
``````

EDITED: now should work

I like your approachπ Thanks for sharing itπ
I though about reduce, but for some reasons didn't give it a shot.

But this solution won't pass the tests. It'll always return [0, 0]
I assume you made a few typos, it happens to me all the time))

I'd change it like this:

1. add (input && input.length) for edge cases
2. Math.min(0, nSum) change to Math.min(0, curr)
3. pSum + Math.max(0, pSum) change to pSum += (curr >= 1 && 1)
``````function countPositivesSumNegatives(input) {
return (input && input.length)
? input.reduce(([pSum, nSum], curr) => [pSum += (curr >= 1 && 1), nSum + Math.min(0, curr)], [0, 0])
: [];
}
``````

I think it might look like this.