Created
March 10, 2022 09:23
-
-
Save DavidWells/ee5df90c120c3b9f3e41df25cbdf9771 to your computer and use it in GitHub Desktop.
Defer execution of function and preserve arguments. Aka thunkify
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
// via https://www.oreilly.com/library/view/you-dont-know/9781491905197/ch04.html | |
function foo(x, y) { | |
return x + y | |
} | |
function thunkify(fn) { | |
var args = [].slice.call( arguments, 1 ); | |
return function(cb) { | |
args.push( cb ); | |
return fn.apply( null, args ); | |
}; | |
} | |
var fooThunk = thunkify(foo, 3, 4); | |
// later | |
fooThunk(function(sum) { | |
console.log( sum ); // 7 | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment