In this next code snippet, we’ll show an example to populate an array with numerical data for unit testing, math or array identifiers.

const initializeArrayUntil = (conditionFn, mapFn) => {
  const arr = [];
  let i = 0;
  let el = undefined;
  do {
    el = mapFn(i, el, arr);
    arr.push(el);
    i++;
  } while (!conditionFn(i, el, arr));
  return arr;
};

initializeArrayUntil(
  (i, val) => val > 10,
  (i, val, arr) => (i <= 1 ? 1 : val + arr[i - 2])
); // [1, 1, 2, 3, 5, 8, 13]

CC BY 4.0 added intro and tags – 30 Seconds of Code

Tags: array, array population, array data, unit testing, fake data, math, array id, numerical data, array manipulation, function, method, javascript, js