Skip to content

Instantly share code, notes, and snippets.

@cuipengfei
Last active December 31, 2015 09:59
Show Gist options
  • Select an option

  • Save cuipengfei/7969951 to your computer and use it in GitHub Desktop.

Select an option

Save cuipengfei/7969951 to your computer and use it in GitHub Desktop.
functional js trampoline
function repeat(operation, num) {
if (num <= 0) {
return num
}
else {
operation()
num--
return num
}
}
function trampoline(fn, op, num) {
while ((num = fn(op, num) ) > 0) {
}
}
module.exports = function (operation, num) {
return trampoline(repeat, operation, num)
}
function repeat(operation, num) {
if (num <= 0) return
return function() {
operation()
return repeat(operation, --num)
}
}
function trampoline(fn) {
while(fn && typeof fn === 'function') {
fn = fn()
}
}
module.exports = function(operation, num) {
trampoline(function() {
return repeat(operation, num)
})
}
@cuipengfei

Copy link
Copy Markdown
Author

the catch is that the repeat function either returns undefined, or a new function that wraps a smaller number

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