Skip to content

Instantly share code, notes, and snippets.

@DavidWells
Created March 10, 2022 09:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidWells/ee5df90c120c3b9f3e41df25cbdf9771 to your computer and use it in GitHub Desktop.
Save DavidWells/ee5df90c120c3b9f3e41df25cbdf9771 to your computer and use it in GitHub Desktop.
Defer execution of function and preserve arguments. Aka thunkify
// 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