Home > katas > Sum of positive (8kyu) [TypeScript]

Sum of positive (8kyu) [TypeScript]


Chek kata on Codewars

Description:

You get an array of numbers, return the sum of all of the positives ones.

Example [1,-4,7,12] => 1 + 7 + 12 = 20

Note: if there is nothing to sum, the sum is default to 0.

Solution 1

Let's use reduce() method to solve this task. It executes a reducer function (that you provide) on each element of the array, resulting in single output value. It is almost a textbook example for reducer.

export function positiveSum(arr: number[]): number {
    const reducer = (accumulator: number, current: number) => accumulator + (current > 0 ? current : 0)
    return arr.reduce(reducer, 0);
}

There are a few variations of this solution. The main difference is how we check if the number is positive or not.

Solution 1.1

export const positiveSum = (arr: number[]) => arr.reduce((accumulator: number, current: number) => current > 0 ? accumulator + current : accumulator, 0)

Solution 1.2

export const positiveSum = (arr: number[]) => arr.filter(num => num > 0).reduce((accumulator: number, current: number) => accumulator + current, 0)

Solution 1.3

export const positiveSum = (arr: number[]) => arr.reduce((accumulator: number, current: number) => accumulator + Math.max(current, 0), 0)

Solution 2

For loop will do the trick as well.

export function positiveSum(arr: number[]): number {
    let sum: number = 0
    for(let i = 0; i < arr.length; i++) {
        if(arr[i] > 0) {
            sum += arr[i]
        }
    }

    return sum
}

Solution 2.1

Or forEach loop also works fine.

export function positiveSum(arr: number[]): number {
    let sum: number = 0
    arr.forEach((num) => num > 0 && (sum += num))
    return sum
}
© 2021, Andrew Losseff