'use strict'; var toArray = require('./array').toArray; var argsToArray = function argsToArray(fn) { // must not be a fat arrow since it breaks the arguments return function () { return fn(toArray(arguments)); }; }; var curry = function curry(fn) { return function curried() { var that = this; for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (args.length < fn.length) { return curried.bind.apply(curried, [that].concat(args)); } else { return fn.apply(that, args); } }; }; var combine = argsToArray(function (fns) { return fns.reverse().reduce(function (fnc, fn) { return function (val) { return fnc(fn(val)); }; }); }); // cannot use fat arrow function since we don't get the arguments, then var promisify = function promisify(fn) { var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; return function () { // copy passed arguments to a new array var args = toArray(arguments); return new Promise(function (resolve, reject) { // add a callback to the arguments, which resolves the promise with the result args.push(function (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 */ var enqueue = function enqueue(promiseGenerators) { return promiseGenerators.reduce(function (f, promiseGenerator) { return function () { 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 */ var enqueueWithResults = function () { var fnQueue = function fnQueue(results, promiseGenerators) { return promiseGenerators.reduce(function (f, promiseGenerator) { return function () { return f().then(function (result) { results.push(result); return promiseGenerator(); }); }; }); }; return function (promiseGenerators) { return function () { var results = []; return fnQueue(results, promiseGenerators)().then(function (result) { results.push(result); return results; }); }; }; }(); module.exports = { argsToArray: argsToArray, combine: combine, curry: curry, promisify: promisify, enqueue: enqueue, enqueueWithResults: enqueueWithResults };