Created
September 5, 2017 11:19
-
-
Save gautam-bst/82b908989a31b050013c9830e5743de1 to your computer and use it in GitHub Desktop.
new Chainable(4).timesTwo().plusTwo().timesTwo()
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
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