UNPKG

freduce

Version:

The Zero-Dependency Left-To-Right Function Composer!

53 lines (46 loc) 1.42 kB
'use strict'; exports.__esModule = true; var identity = function identity(x) { return x; }; var always = function always(x) { return function () { return x; }; }; var isFunction = function isFunction(f) { return !!(f && f.constructor && f.call && f.apply); }; var isReducible = function isReducible(a) { return !!(a && typeof a.reduce === 'function'); }; var isThenable = function isThenable(p) { return typeof p.then === 'function'; }; /** * freduce: Function Reducer * * Composes from left-to-right, so d(c(b(a(x)))) is * equivalent to freduce(a,b,c,d)(x) * * @param {...Function} A list of functions * @returns {Function} A composite function */ var freduce = function freduce(first) { for (var _len = arguments.length, rest = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { rest[_key - 1] = arguments[_key]; } if (!first) return identity; if (isReducible(first)) first = freduce.apply(undefined, first); if (!isFunction(first)) return always(first); if (!rest) return first; return function () { return rest.reduce(reducer, first.apply(undefined, arguments)); }; }; var reducer = exports.reducer = function reducer(previousResult, freddy) { var f = freduce(freddy); if (isThenable(previousResult)) return previousResult.then(f); return f(previousResult); }; exports['default'] = freduce;