DEV Community

Kuncheria Kuruvilla
Kuncheria Kuruvilla

Posted on • Edited on

4 3

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)), ...]
Enter fullscreen mode Exit fullscreen mode

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)];
}
Enter fullscreen mode Exit fullscreen mode

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));

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay