Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do <something> N times (declarative syntax)

Just use a for loop:

var times = 10;

for(var i = 0; i < times; i++){
    doSomething();
}

Possible ES6 alternative.

Array.from(Array(3)).forEach((x, i) => {
  something();
});

And, if you want it "to be called 1,2 and 3 times respectively".

Array.from(Array(3)).forEach((x, i) => {
  Array.from(Array(i+1)).forEach((x, i2) => {
    console.log(`Something ${ i } ${ i2 }`)
  });
});

Update:

Taken from filling-arrays-with-undefined

This seems to be a more optimised way of creating the initial array, I've also updated this to use the second parameter map function suggested by @felix-eve.

Array.from({ length: 3 }, (x, i) => {
  something();
});

This answer is based on Array.forEach, without any library, just native vanilla.

To basically call something() 3 times, use:

[1,2,3].forEach(function(i) {
  something();
});

considering the following function:

function something(){ console.log('something') }

The output will be:

something
something
something

To complete this questions, here's a way to do call something() 1, 2 and 3 times respectively:

It's 2017, you may use ES6:

[1,2,3].forEach(i => Array(i).fill(i).forEach(_ => {
  something()
}))

or in good old ES5:

[1,2,3].forEach(function(i) {
  Array(i).fill(i).forEach(function() {
    something()
  })
}))

In both cases, the output will be

The output will be:

something

something
something

something
something
something

(once, then twice, then 3 times)


Create an Array and fill all items with undefined before using map:

👉 Read detailed reason why map is skipping never-defined array items

⚠️ Array.fill has no IE support

Array(5).fill().map((item, i) => console.log(item, i))

Or fill do the same as above without fill, by destructuring the Array, which automatically sets undefined for each item, if the item's value was not set:

[...Array(5)].map((item, i) => console.log(item, i))

If you want to make the above more "declarative", my currently opinion-based solution would be:

const iterate = times => callback => [...Array(times)].map((n,i) => callback(i))

iterate(3)(console.log)

Using old-school (reverse) loop:

// run 5 times:
for( let i=5; i--; )
   console.log(i) 

Or as a declarative "while":

const run = (cb, ...args) => count => { while(count--) cb(...args) }

// executes the callback with whatever arguments, 3 times
run(console.log, 1,2,3)(3)