function.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. 'use strict';
  2. const toArray = require('./array').toArray;
  3. const argsToArray = fn => {
  4. // must not be a fat arrow since it breaks the arguments
  5. return function () {
  6. return fn(toArray(arguments));
  7. };
  8. };
  9. const curry = fn => {
  10. return function curried (...args) {
  11. const that = this;
  12. if (args.length < fn.length) {
  13. return curried.bind.apply(curried, [that].concat(args));
  14. } else {
  15. return fn.apply(that, args);
  16. }
  17. };
  18. };
  19. const combine = argsToArray(fns => fns.reverse().reduce((fnc, fn) => val => fnc(fn(val))));
  20. // cannot use fat arrow function since we don't get the arguments, then
  21. const promisify = (fn, context = null) => function () {
  22. // copy passed arguments to a new array
  23. const args = toArray(arguments);
  24. return new Promise((resolve, reject) => {
  25. // add a callback to the arguments, which resolves the promise with the result
  26. args.push((err, data) => {
  27. if (err) {
  28. reject(err);
  29. } else {
  30. resolve(data);
  31. }
  32. });
  33. // call the original function with our callback flavoured arguments
  34. fn.apply(context, args);
  35. });
  36. };
  37. /**
  38. returns a function which executes promises one after another
  39. @param promiseGenerators an array of functions which return a promise
  40. @return function which executes the promises
  41. */
  42. const enqueue = (promiseGenerators) => {
  43. return promiseGenerators.reduce((f, promiseGenerator) => {
  44. return () => {
  45. return f().then(promiseGenerator);
  46. };
  47. });
  48. };
  49. /**
  50. Returns a function which executes promises one after another. The resulting function
  51. returns a promise, which gets filled with an array of the results of the single promises.
  52. @param promiseGenerators an array of functions which return a promise
  53. @return function which executes the promises
  54. */
  55. const enqueueWithResults = (function () {
  56. const fnQueue = (results, promiseGenerators) => promiseGenerators.reduce((f, promiseGenerator) => {
  57. return () => {
  58. return f().then(result => {
  59. results.push(result);
  60. return promiseGenerator();
  61. });
  62. };
  63. });
  64. return function (promiseGenerators) {
  65. return () => {
  66. const results = [];
  67. return fnQueue(results, promiseGenerators)().then(result => {
  68. results.push(result);
  69. return results;
  70. });
  71. };
  72. };
  73. }());
  74. module.exports = {
  75. argsToArray,
  76. combine,
  77. curry,
  78. promisify,
  79. enqueue,
  80. enqueueWithResults
  81. };