Bonfire 35: Steamroller

TASK: Flatten a nested array. You must account for varying levels of nesting.

I must admit I am still struggling with this stuff, but hey, it’s recursive and it works!
I’m much, much in debt to Jai’s solution on this thread.


function steamroller(arr) {


if (Array.isArray(arr) && arr.length > 0) {
var head = arr[0];
var tail = arr.slice(1);

return steamroller(head).concat(steamroller(tail));
} else {
return [].concat(arr);
}
};


steamroller([1, [2], [3, [[4]]]]);

Advertisements
Bonfire 35: Steamroller

Bonfire 04: Factorialize a Number

TASK: Return the factorial of the provided integer.


function factorialize(num) {
 
 if(num===0) {
 return 1;
 }
 return num * factorialize(num-1);
}

factorialize(5)

A recursive function is a function that calls itself until it doesn’t. In this case, it multiplies num * (num-1) until (num-1) = 0, when it multiplies the number obtained so far by 1.

Resources:

Bonfire 04: Factorialize a Number