Skip to content

Instantly share code, notes, and snippets.

@pseudosavant
Created October 21, 2022 18:02
Show Gist options
  • Save pseudosavant/a1e338fbd21f233b5046625ef4c3dc37 to your computer and use it in GitHub Desktop.
Save pseudosavant/a1e338fbd21f233b5046625ef4c3dc37 to your computer and use it in GitHub Desktop.
Simple JavaScript for loops
// Alternate for loop that is more of a functional style
// `fr` accepts two arguments.
// The first argument expects an Array (to get the length of it) or a number. Passing in an array is similar to `myArray.forEach()`.
// The second argument is a function with the signature `(currentIteration, totalIterations)`
const fr = (iterationsOrArray, fn) => {
if (typeof iterationsOrArray !== 'number'&& !Array.isArray(iterationsOrArray)) {
throw new TypeError('Invalid argument: expected an `Array` or `number` for the first argument');
}
let iterations = (Array.isArray(iterationsOrArray) ? iterationsOrArray.length : iterationsOrArray);
if (typeof fn !== 'function') {
throw new TypeError('Invalid argument: expected a `function` for the second argument');
}
for (let i = 0; i < iterations; i++) {
fn(i, iterations);
}
}
// Usage examples
// Loop an arbitrary number of times
fr(5, (i) => console.log(i));
// 0
// 1
// 2
// 3
// 4
// Loop over every entry in an array
const myArray = [1,2,3];
let text = '';
fr(myArray, (i, iterations) => text += `iteration ${myArray[i]} of ${iterations}\r\n`);
console.log(text);
// iteration 1 of 3
// iteration 2 of 3
// iteration 3 of 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment