Files
lodash/lodash.flow/index.js
2018-02-03 19:13:29 -08:00

74 lines
1.9 KiB
JavaScript

/**
* lodash (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright jQuery Foundation and other contributors <https://jquery.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
var baseFlatten = require('lodash._baseflatten'),
rest = require('lodash.rest');
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/**
* Creates a `_.flow` or `_.flowRight` function.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new flow function.
*/
function createFlow(fromRight) {
return rest(function(funcs) {
funcs = baseFlatten(funcs, 1);
var length = funcs.length,
index = length;
if (fromRight) {
funcs.reverse();
}
while (index--) {
if (typeof funcs[index] != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
}
return function() {
var index = 0,
result = length ? funcs[index].apply(this, arguments) : arguments[0];
while (++index < length) {
result = funcs[index].call(this, result);
}
return result;
};
});
}
/**
* Creates a function that returns the result of invoking the given functions
* with the `this` binding of the created function, where each successive
* invocation is supplied the return value of the previous.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Util
* @param {...(Function|Function[])} [funcs] Functions to invoke.
* @returns {Function} Returns the new composite function.
* @see _.flowRight
* @example
*
* function square(n) {
* return n * n;
* }
*
* var addSquare = _.flow(_.add, square);
* addSquare(1, 2);
* // => 9
*/
var flow = createFlow();
module.exports = flow;