123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- 'use strict';
- const toArray = require('./array').toArray;
- const argsToArray = fn => {
- // must not be a fat arrow since it breaks the arguments
- return function () {
- return fn(toArray(arguments));
- };
- };
- const curry = fn => {
- return function curried (...args) {
- const that = this;
- if (args.length < fn.length) {
- return curried.bind.apply(curried, [that].concat(args));
- } else {
- return fn.apply(that, args);
- }
- };
- };
- const combine = argsToArray(fns => fns.reverse().reduce((fnc, fn) => val => fnc(fn(val))));
- // cannot use fat arrow function since we don't get the arguments, then
- const promisify = (fn, context = null) => function () {
- // copy passed arguments to a new array
- const args = toArray(arguments);
- return new Promise((resolve, reject) => {
- // add a callback to the arguments, which resolves the promise with the result
- args.push((err, data) => {
- if (err) {
- reject(err);
- } else {
- resolve(data);
- }
- });
- // call the original function with our callback flavoured arguments
- fn.apply(context, args);
- });
- };
- /**
- returns a function which executes promises one after another
- @param promiseGenerators an array of functions which return a promise
- @return function which executes the promises
- */
- const enqueue = (promiseGenerators) => {
- return promiseGenerators.reduce((f, promiseGenerator) => {
- return () => {
- return f().then(promiseGenerator);
- };
- });
- };
- /**
- Returns a function which executes promises one after another. The resulting function
- returns a promise, which gets filled with an array of the results of the single promises.
- @param promiseGenerators an array of functions which return a promise
- @return function which executes the promises
- */
- const enqueueWithResults = (function () {
- const fnQueue = (results, promiseGenerators) => promiseGenerators.reduce((f, promiseGenerator) => {
- return () => {
- return f().then(result => {
- results.push(result);
- return promiseGenerator();
- });
- };
- });
- return function (promiseGenerators) {
- return () => {
- const results = [];
- return fnQueue(results, promiseGenerators)().then(result => {
- results.push(result);
- return results;
- });
- };
- };
- }());
- module.exports = {
- argsToArray,
- combine,
- curry,
- promisify,
- enqueue,
- enqueueWithResults
- };
|