Home > katas > Count of positives / sum of negatives (8kyu) [JavaScript]

Count of positives / sum of negatives (8kyu) [JavaScript]


Chek kata on Codewars

Description:

Given an array of integers.

Return an array, where the first element is the count of positives numbers and the second element is sum of negative numbers.

If the input array is empty or null, return an empty array.

For input [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15], you should return [10, -65].

Loop

function countPositivesSumNegatives(input) {
    const answer = []
    let positiveSum = 0
    let negativeSum = 0

    if(input && input.length) {
      for(let i = 0; i < input.length; i++) {
        if(input[i] > 0) {
            positiveSum += 1
        } else {
            negativeSum += input[i]
        }
      }
      answer.push(positiveSum)
      answer.push(negativeSum)
    }
    return answer
}

Filter and reduce

function countPositivesSumNegatives(input) {
    return (input && input.length) ? [input.filter(num => num > 0).length, input.filter(num => num < 0).reduce((acc, cur) => acc + cur, 0)] : []
}

Reduce

function countPositivesSumNegatives(input) {
   return (input && input.length)
    ? input.reduce(([pSum, nSum], curr) => [pSum += (curr >= 1 && 1), nSum + Math.min(0, curr)], [0, 0])
    : [];
}

ForEach

function countPositivesSumNegatives(input) {
    if (input && input.length) {
        let positiveSum = 0
        let negativeSum = 0
        input.forEach(num => num > 0 ? positiveSum++ : negativeSum += num)
        return [positiveSum, negativeSum]
    } else {
        return []
    }
}
© 2021, Andrew Losseff