1.1 KiB
1.1 KiB
title, type, language, tags, author, cover, dateModified
| title | type | language | tags | author | cover | dateModified | |
|---|---|---|---|---|---|---|---|
| Initialize array until | snippet | javascript |
|
chalarangelo | neon-desk-2 | 2023-06-22T05:00:00-04:00 |
Initializes and fills an array with values generated by a function, until a condition is met.
- Create an empty array,
arr, an index variableiand an elementel. - Use a
do...whileloop to add elements to the array, using themapFnfunction, until theconditionFnfunction returnstruefor the given indexiand elementel. - The condition function,
conditionFn, takes three arguments: the current index, the previous element and the array itself. - The mapping function,
mapFn, takes three arguments: the current index, the current element and the array itself.
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]