Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS - repeat action N times without a for or while loop?

For example, I want to create some debug data array and I need a function that will take only the length of desired array and return array of objects with few props with random data values.

Is there a way to make this function without a for loop? The reason for the question is that I have this i variable that I don't really need.

const generateData = (count) => {
  let data = []
  for (let i = 0; i < count; i++)  
    data.push({
      foo: Math.round(Math.random() * 100),
      bar: Math.random() > 0.5
    })
  return data  

}
like image 936
stdnik Avatar asked Dec 13 '22 13:12

stdnik


1 Answers

You can create the array all at once with Array.from, if you want, no declaration or usage of any intermediate variable names:

const generateData = length => (
  Array.from(
    { length },
    () => ({
      foo: Math.round(Math.random() * 100),
      bar: Math.random() > 0.5
    })
  )
);
console.log(generateData(5));
like image 93
CertainPerformance Avatar answered Jan 31 '23 04:01

CertainPerformance