[codewars] Count of positives / sum of negatives

KJA·2022년 8월 19일
0

https://www.codewars.com/kata/576bb71bbbcf0951d5000044


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. 0 is neither positive nor negative.

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

Example

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

문제 해결

function countPositivesSumNegatives(input) {
    let positive = 0;
    let negative = 0;
    if (input === null || input.length < 1) return [];
    input.forEach((v) => (v > 0 ? positive++ : (negative += v)));
    return [positive, negative];
}

다른 풀이

filter 사용

function countPositivesSumNegatives(input) {
    return input && input.length ? [input.filter(p => p > 0).length, input.filter(n => n < 0).reduce((a, b) => a + b, 0)] : [];
}

0개의 댓글