Lets cut to the chase and look at what we are trying to do here. We need to write a function that can spit an array of any given size, such that every element is obtained by applying a function on the previous element.
Let us consider an initial element x
and a function f
, what we need is an array which looks something like this :
[x, f(x), f(f(x)), ...]
Well, the simplest application of such a function would be to create a series of numbers like , squares of 2 : 1 ,2, 4, 8 ..
Now lets look at how we can write such a function
function iterate(fn, ele, n) {
if (n === 0) return [];
return [ele, ...iterate(fn, fn(ele), n - 1)];
}
Our function iterate
, returns a list of repeated applications of fn
to ele
, repeated n
number of times:
Lets try out some examples
The initial item and the function you apply can be anything that you can think of. You could easily create a list of dummy products take a look at the example:
Top comments (0)