Skip to content

Instantly share code, notes, and snippets.

@kdubbels
Created August 19, 2020 00:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kdubbels/ef8e1e58073bdd80b37107a158d1a26d to your computer and use it in GitHub Desktop.
Save kdubbels/ef8e1e58073bdd80b37107a158d1a26d to your computer and use it in GitHub Desktop.
Write a higher-order function loop that provides something like a for loop statement. It takes a value, a test function, an update function, and a body function. Each iteration, it first runs the test function on the current loop value and stops if that returns false. Then it calls the body function, giving it the current value. Finally, it call…
// Write a higher-order function loop that provides something like a for loop statement.
// It takes a value, a test function, an update function, and a body function. Each
// iteration, it first runs the test function on the current loop value and stops if
// that returns false. Then it calls the body function, giving it the current value.
// Finally, it calls the update function to create a new value and starts from the beginning.
// When defining the function, you can use a regular loop to do the actual looping.
const loop = (value, testFunc, updateFunc, bodyFunc) => {
if (testFunc(value)) {
bodyFunc(value)
loop(updateFunc(value), testFunc, updateFunc, bodyFunc)
}
}
loop(3, n => n > 0, n => n - 1, console.log);
// → 3
// → 2
// → 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment