New article, new snippets, new collection
This commit is contained in:
37
snippets/js/s/initialize-array-while.md
Normal file
37
snippets/js/s/initialize-array-while.md
Normal file
@ -0,0 +1,37 @@
|
||||
---
|
||||
title: Initialize array while
|
||||
type: snippet
|
||||
language: javascript
|
||||
tags: [array]
|
||||
author: chalarangelo
|
||||
cover: neon-desk-1
|
||||
dateModified: 2023-06-20T05:00:00-04:00
|
||||
---
|
||||
|
||||
Initializes and fills an array with values generated by a function, while a condition is met.
|
||||
|
||||
- Create an empty array, `arr`, an index variable `i` and an element `el`.
|
||||
- Use a `while` loop to add elements to the array, using the `mapFn` function, as long as the `conditionFn` function returns `true` for the given index `i` and element `el`.
|
||||
- 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.
|
||||
|
||||
```js
|
||||
const initializeArrayWhile = (conditionFn, mapFn) => {
|
||||
const arr = [];
|
||||
let i = 0;
|
||||
let el = mapFn(i, undefined, arr);
|
||||
while (conditionFn(i, el, arr)) {
|
||||
arr.push(el);
|
||||
i++;
|
||||
el = mapFn(i, el, arr);
|
||||
}
|
||||
return arr;
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
initializeArrayWhile(
|
||||
(i, val) => val < 10,
|
||||
(i, val, arr) => (i <= 1 ? 1 : val + arr[i - 2])
|
||||
); // [1, 1, 2, 3, 5, 8]
|
||||
```
|
||||
Reference in New Issue
Block a user