Introduction
In this lab, we will explore the concept of initializing and filling an array with values generated by a function until a specific condition is met. We will be using the initializeArrayUntil function which takes two arguments: conditionFn and mapFn. Through this lab, you will gain a deeper understanding of how to use this function to generate arrays with custom values and conditions.
How to Initialize an Array Until a Condition is Met
To start practicing coding, open the Terminal/SSH and type node.
Here are the steps to initialize and fill an array with values generated by a function until a certain condition is met:
- Create an empty array
arr, an index variablei, and an elementel. - Use a
do...whileloop to add elements to the array using themapFnfunction until theconditionFnfunction returnstruefor the given indexiand elementel. - The
conditionFnfunction takes three arguments: the current index, the previous element, and the array itself. - The
mapFnfunction takes three arguments: the current index, the current element, and the array itself.
Here's the code:
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;
};
To use the initializeArrayUntil function, provide two functions as arguments:
initializeArrayUntil(
(i, val) => val > 10, //conditionFn
(i, val, arr) => (i <= 1 ? 1 : val + arr[i - 2]) //mapFn
); // [1, 1, 2, 3, 5, 8, 13]
This code initializes an array with the Fibonacci sequence up to the first number greater than 10. The conditionFn function checks if the current value is greater than 10, and the mapFn function generates the next number in the sequence.
Summary
Congratulations! You have completed the Initialize Array Until lab. You can practice more labs in LabEx to improve your skills.