## DEV Community

Kuncheria Kuruvilla

Posted on • Updated on

# iterate , iterate, iterate

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

``` function iterate(fn, ele, iterationCount) { if (iterationCount === 0) return []; return [ele, ...iterate(fn, fn(ele), iterationCount - 1)]; } ``` ``` const multiply = (x) => (y) => x * y; console.log(iterate(multiply(2), 1, 5)); ```

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:

``` function iterate(fn, ele, iterationCount) { if (iterationCount === 0) return []; return [ele, ...iterate(fn, fn(ele), iterationCount - 1)]; } ``` ``` const initialProduct = { id: 100, slug: `prd\${100}`, name: `Product-\${100}` }; const createNextProduct = (product) => { const nextProductId = product.id + 1; return { id: nextProductId, slug: `prd\${nextProductId}`, name: `Product-\${nextProductId}`, }; }; console.log(iterate(createNextProduct, initialProduct, 5)); ```