Skip to content

Instantly share code, notes, and snippets.

@mediaupstream
Created February 25, 2018 03:46
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 mediaupstream/cf1b8c6c112008bd9bfc536b4c0964b7 to your computer and use it in GitHub Desktop.
Save mediaupstream/cf1b8c6c112008bd9bfc536b4c0964b7 to your computer and use it in GitHub Desktop.
repeat a function n number of times.
function repeat(n = 1) {
let i = 0;
return fn => {
while(n--) {
i++;
fn(i)
}
}
}
// example usage:
repeat(10)(i => {
console.log('floop boop', i)
})
@mediaupstream
Copy link
Author

repeat is a higher order function (it returns a function). The function returned by calling repeat(10) accepts a function as a parameter. That function will get called 10 times, each time it's called it passes the iteration number to the function as a parameter... in case you wanted it.

The function you provide will get called n times but it's called pretty much simultaneously. So like it doesn't wait for the function to complete before calling it again... if that makes sense...

@bmoren
Copy link

bmoren commented Feb 25, 2018

Thanks for this. I think this is on track, is there a way (is it even possible) to get rid of the anon function and instead just have curly braces as a direct function? leaving the i out of the mix entirely (at least what would be exposed to the end user of the function!?

so instead of

repeat(10)(i => {
  console.log('floop boop', i)
})

we'd have something like

let i = 0;
repeat(10){
   i++
   console.log('floop boop', i)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment