Exercise 3 solution
-
In notebook:
-
FrontEndMasters Functional light
-
Created at:
-
2016-09-24
-
Updated:
-
2016-09-24
-
Tags:
-
Functional Programming JavaScript
function mult(...args) {
// base case
// all recursive functions should have a base case so they don't run forever
if (args.length <= 2) {
return args[0] * args[1];
}
// recursive (reductive) call
return args[0] * mult(...args.slice(1));
}
mult(3,4,5); // 60
mult(3,4,5,6); // 360
Note:
.slice
does not mutate the array. It creates a new array.
.splice
actually changes the array in place. So not all methods are immutable.
This is
not proper tail call since calling
mult
is not the last expression there's a multiplication after that.