pipeline.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /** @license MIT License (c) copyright 2011-2013 original author or authors */
  2. /**
  3. * pipeline.js
  4. *
  5. * Run a set of task functions in sequence, passing the result
  6. * of the previous as an argument to the next. Like a shell
  7. * pipeline, e.g. `cat file.txt | grep 'foo' | sed -e 's/foo/bar/g'
  8. *
  9. * @author Brian Cavalier
  10. * @author John Hann
  11. */
  12. (function(define) {
  13. define(function(require) {
  14. var when = require('./when');
  15. var all = when.Promise.all;
  16. var slice = Array.prototype.slice;
  17. /**
  18. * Run array of tasks in a pipeline where the next
  19. * tasks receives the result of the previous. The first task
  20. * will receive the initialArgs as its argument list.
  21. * @param tasks {Array|Promise} array or promise for array of task functions
  22. * @param [initialArgs...] {*} arguments to be passed to the first task
  23. * @return {Promise} promise for return value of the final task
  24. */
  25. return function pipeline(tasks /* initialArgs... */) {
  26. // Self-optimizing function to run first task with multiple
  27. // args using apply, but subsequence tasks via direct invocation
  28. var runTask = function(args, task) {
  29. runTask = function(arg, task) {
  30. return task(arg);
  31. };
  32. return task.apply(null, args);
  33. };
  34. return all(slice.call(arguments, 1)).then(function(args) {
  35. return when.reduce(tasks, function(arg, task) {
  36. return runTask(arg, task);
  37. }, args);
  38. });
  39. };
  40. });
  41. })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });