Advertisement
Guest User

Untitled

a guest
Sep 24th, 2017
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.73 KB | None | 0 0
  1. // First approach: pass functions as arguments for chaining. Executes from left to right;
  2. // Please, run with node >= 8 (because of asserts)
  3.  
  4. function chain() {
  5. let funcs = [...arguments];
  6. let finish;
  7.  
  8. function run(acc) {
  9. if (funcs.length > 0) {
  10. const func = funcs.shift();
  11. if (typeof func === 'function') {
  12. func(acc, (err, res) => {
  13. if (err) {
  14. finish(err);
  15. } else {
  16. run.call(null, res);
  17. }
  18. });
  19. }
  20. } else {
  21. finish(null, acc);
  22. }
  23. }
  24.  
  25. return function (number, cb) {
  26. finish = cb;
  27.  
  28. run(number);
  29. }
  30. }
  31.  
  32. var shouldBeTwelve = chain(plusTwo, timesTwo, plusTwo);
  33.  
  34. shouldBeTwelve(3, (err, result) => {
  35. assert.equal(result, 12)
  36. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement