Consider the following implementation of take
:
const take = (n, [x, ...xs]) =>
n === 0 || x === undefined ?
[] : [x, ...take(n - 1, xs)];
console.log(take(7, [1, 2, 3, 4, 5])); // [1, 2, 3, 4, 5]
console.log(take(3, [1, 2, 3, 4, 5])); // [1, 2, 3]
console.log(take(1, [undefined, 1])); // []
As you can see, it doesn't work for arrays with undefined
because x === undefined
is not the best way to test whether an array is empty. The following code fixes this problem:
const take = (n, xs) =>
n === 0 || xs.length === 0 ?
[] : [xs[0], ...take(n - 1, xs.slice(1))];
console.log(take(7, [1, 2, 3, 4, 5])); // [1, 2, 3, 4, 5]
console.log(take(3, [1, 2, 3, 4, 5])); // [1, 2, 3]
console.log(take(1, [undefined, 1])); // [undefined]
However, writing xs[0]
and xs.slice(1)
isn't as elegant. In addition, it's problematic if you need to use them multiple times. Either you'll have to duplicate code and do unnecessary extra work, or you'll have to create a block scope, define constants and use the return keyword.
The best solution would be to use a let expression. Unfortunately, JavaScript doesn't have them. So, how to simulate let expressions in JavaScript?