Created
February 25, 2018 03:46
-
-
Save mediaupstream/cf1b8c6c112008bd9bfc536b4c0964b7 to your computer and use it in GitHub Desktop.
repeat a function n number of times.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function repeat(n = 1) { | |
let i = 0; | |
return fn => { | |
while(n--) { | |
i++; | |
fn(i) | |
} | |
} | |
} | |
// example usage: | |
repeat(10)(i => { | |
console.log('floop boop', i) | |
}) |
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
repeat
is a higher order function (it returns a function). The function returned by callingrepeat(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...