Skip to content

Instantly share code, notes, and snippets.

@gautam-bst
Created September 5, 2017 11:19
Show Gist options
  • Save gautam-bst/82b908989a31b050013c9830e5743de1 to your computer and use it in GitHub Desktop.
Save gautam-bst/82b908989a31b050013c9830e5743de1 to your computer and use it in GitHub Desktop.
new Chainable(4).timesTwo().plusTwo().timesTwo()
var assert = require('assert');
var isNumber = function (number) {
return typeof number === 'number';
};
var timesTwo = function (number, callback) {
process.nextTick(function () {
if (isNumber(number)) {
callback(null, number * 2);
}
else {
callback(new Error('You did not pass a number'));
}
});
};
var plusTwo = function (number, callback) {
process.nextTick(function () {
if (isNumber(number)) {
callback(null, number + 2);
}
else {
callback(new Error('You did not pass a number'));
}
});
};
var timesTwoPlusTwo = function (number, callback) {
timesTwo(number, function (err, result) {
if (err) {
callback(err);
}
plusTwo(result, callback);
});
};
class Chainable{
constructor(i){
this.val = i;
}
timesTwo () {
this.val *= 2;
return this
}
plusTwo () {
this.val += 2;
return this
}
}
console.log(new Chainable(4).timesTwo().plusTwo().timesTwo());
// 1. new Chainable(4).timesTwo().plusTwo().timesTwo() = 20
// 2. const chainedFunctions = chain(timesTwo, plusTwo, plusTwo, timesTwo);
// chainedFunctions(4) = 48
timesTwoPlusTwo(4, function (err, result) {
assert.equal(result, 10);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment