DEV Community

loading...

Count of positives / sum of negatives with JavaScript

andrew_losseff profile image Andrew βš›οΈ & β˜• ・1 min read

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)

pic
Editor guide
Collapse
alfredosalzillo profile image
Alfredo Salzillo

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

Collapse
andrew_losseff profile image
Andrew βš›οΈ & β˜• Author

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.