Suppose I have this simple JavaScript function:
function returnArray(){
return [1, 2, 3];
}
Further suppose that I then say
<
Your logical error has been pointed out in comments and answers, but let me point out a cleaner, simpler, less bug-prone way to write this which is more in line with basic principles of recursion.
function double([head, ...tail]) {
if (head === undefined) return [];
return [2*head, ...double(tail)];
}
In other words, there is only one "base case", namely the empty array, which returns an empty array. Everything else is simple recursion.
You could "functionalize" this further with
function map(fn) {
return function iter([head, ...tail]) {
return head === undefined ? [] : [fn(head), ...iter(tail)];
};
}
const double = map(x => 2*x);
console.log(double([1, 2, 3]));