Home > katas > Counting sheep... (8kyu) [TypeScript]

Counting sheep... (8kyu) [TypeScript]


Chek kata on Codewars

Description:

Consider an array/list of sheep where some sheep may be missing from their place. We need a function that counts the number of sheep present in the array (true means present).

For example,

[true,  true,  true,  false,
  true,  true,  true,  true ,
  true,  false, true,  false,
  true,  false, false, true ,
  true,  true,  true,  true ,
  false, false, true,  true]
The correct answer would be 17.

Hint: Don't forget to check for bad values like null/undefined

Solution 1

Let's start with loop solutions.

export function countSheeps(arrayOfSheep: (boolean | undefined | null)[]) {
    let counter: number = 0
    for(let i = 0; i < arrayOfSheep.length; i++) {
        if (arrayOfSheep[i] === true) counter += 1
    }
    return counter
}

export function countSheeps(arrayOfSheep: (boolean | undefined | null)[]) {
    let counter: number = 0
    arrayOfSheep.forEach(item => {
        if(item) counter++
    })
    return counter
}

Solution 2

Let's solve it with Filter.

export function countSheeps(arrayOfSheep: (boolean | undefined | null)[]) {
    return arrayOfSheep.filter(item => item === true).length
}

export function countSheeps(arrayOfSheep: (boolean | undefined | null)[]) {
    return arrayOfSheep.filter(Boolean).length
}

Solution 3

Let's solve it with reduce().

export function countSheeps(arrayOfSheep: (boolean | undefined | null)[]) {
    return arrayOfSheep.reduce((acc, cur) => acc + (cur === true ? 1 : 0), 0)
}
© 2021, Andrew Losseff