8kyu – positiveSum

The first question is to sum up all the positive integers in an array. Basically two things need to be done:

• Filter out Values that should not be added to the sum
• Sum up every item in the array

Basically you can write the solution like this:

``````export function positiveSum(arr: number[]): number {
return arr
.filter(val => val > 0)
.reduce((total, current) => total + current, 0)
}``````

It is important to note that the initial value of 0 must be set, as if you pass in an empty array it would return `NaN`

7kyu – next Prime

Basically you need to check every number if it `isPrime`. Then you need to select an algorithm that can check if it is a prime number.

In this case I just took the code from the npm package is-number-prime. Which is a brute force way of figuring out if the number is prime or not. (There is probably something more mathematically elegant out there)

``````function isNumberPrime(n) {
if (n === 2 || n === 3){
return true;
}

if (n < 2 || n % 1 || n % 2 === 0 || n % 3 === 0) {
return false;
}
let foo = Math.floor(Math.sqrt(n));
for (let i = 5; i <= foo; i += 6) {
if (n % i === 0 || n % (i + 2) == 0) {
return false;
}
}
return true;
}

function nextPrime(n){
while (true){
n++;
if (isNumberPrime(n)){
return n;
}
}
}``````

8kyu – Logic Drills: Traffic light

You need a function to handle each change from green, to yellow, to red, and then to green again.

Based on how the question is formulated it is suggested that you should always return the next item in an array. If it is the last item it should return the first item.

``````/**
*
* @param {'green'| 'yellow'| 'red'} current
* @returns {string}
*/
function updateLight(current) {
let lights = ['green', 'yellow', 'red'];
let nextIndex = (lights.indexOf(current) + 1) % lights.length;
return lights[nextIndex];
}``````

However as alternative you also could say: We always already know the next state, we do not need to calculate the next state. For traffic lights this system also probably will never change. Thus you can use an object to save the next states.

``````/**
*
* @param {'green'| 'yellow'| 'red'} current
* @returns {string}
*/
function updateLight2(current) {
return {
'green': 'red',
'yellow': 'green',
'red': 'yellow'
}[current];
}``````

7kyu – Sum of numerous arguments

The idea of this problem is mostly to make aware of that you can pass in an arbitrary amount of arguments into a js function.

In ES5 you would be using the `arguments` object and iterate over the array. in ES6 however we can use the cleaner spread-syntax:

``````/**
*
* @param {number[]} args
* @returns {number}
*/
function findSum(...args){
if (args.find(val => val < 0)){
return -1;
} else {
return [...arguments].reduce((total, current) => total + current);
}
}``````