function.js 2.6 KB

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