Created
January 18, 2018 03:08
-
-
Save xinlc/e6d37b3085ef723d1a2aa869a718cbc8 to your computer and use it in GitHub Desktop.
Turn a regular node function into one which returns a thunk
This file contains hidden or 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
// ES5版本 | |
var Thunk = function(fn){ | |
return function (){ | |
var args = Array.prototype.slice.call(arguments); | |
return function (callback){ | |
args.push(callback); | |
return fn.apply(this, args); | |
} | |
}; | |
}; | |
/* | |
function f(a, cb) { | |
cb(a); | |
} | |
const ft = Thunk(f); | |
ft(1)(console.log) // 1 | |
*/ |
This file contains hidden or 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
// ES6版本 | |
const Thunk = function(fn) { | |
return function (...args) { | |
return function (callback) { | |
return fn.call(this, ...args, callback); | |
} | |
}; | |
}; |
This file contains hidden or 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
// node-Thunkify | |
function thunkify(fn) { | |
return function() { | |
var args = new Array(arguments.length); | |
var ctx = this; | |
for (var i = 0; i < args.length; ++i) { | |
args[i] = arguments[i]; | |
} | |
return function (done) { | |
var called; | |
args.push(function () { | |
if (called) return; | |
called = true; | |
done.apply(null, arguments); | |
}); | |
try { | |
fn.apply(ctx, args); | |
} catch (err) { | |
done(err); | |
} | |
} | |
} | |
}; | |
/* | |
function f(a, b, callback){ | |
var sum = a + b; | |
callback(sum); | |
callback(sum); | |
} | |
var ft = thunkify(f); | |
var print = console.log.bind(console); | |
ft(1, 2)(print); | |
// 3 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment