DEV Community

Discussion on: Count of positives / sum of negatives with JavaScript

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

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.