Unfold Array
To create an array using an iterator function and an initial seed value, follow these steps:
- Open the Terminal/SSH and type
node
to start practicing coding.
- Use a
while
loop and Array.prototype.push()
to call the iterator function repeatedly until it returns false
.
- The iterator function should accept one argument (
seed
) and always return an array with two elements ([value
, nextSeed
]) or false
to terminate.
Use the following code to implement the unfold
function:
const unfold = (fn, seed) => {
let result = [],
val = [null, seed];
while ((val = fn(val[1]))) result.push(val[0]);
return result;
};
Here's an example of how to use the unfold
function:
var f = (n) => (n > 50 ? false : [-n, n + 10]);
unfold(f, 10); // [-10, -20, -30, -40, -50]
This will produce an array with values generated by the iterator function f
starting from the initial seed value of 10
. The iterator function generates an array with two elements at each step: the negation of the current seed value and the next seed value, which is incremented by 10. The process continues until the seed value is greater than 50, at which point the function returns false
.