Simplify flow modules.

This commit is contained in:
John-David Dalton
2017-01-11 08:11:00 -08:00
parent 379b7a057c
commit 454219fbfe
3 changed files with 23 additions and 45 deletions

View File

@@ -1,38 +0,0 @@
/**
* 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 (...funcs) => {
const length = funcs.length;
let index = length;
if (fromRight) {
funcs.reverse();
}
while (index--) {
if (typeof funcs[index] !== 'function') {
throw new TypeError('Expected a function');
}
}
return function(...args) {
const value = args[0];
let index = 0;
let result = length ? funcs[index].apply(this, args) : value;
while (++index < length) {
result = funcs[index].call(this, result);
}
return result;
};
};
}
export default createFlow;

22
flow.js
View File

@@ -1,5 +1,3 @@
import createFlow from './.internal/createFlow.js';
/**
* Creates a function that returns the result of invoking the given functions
* with the `this` binding of the created function, where each successive
@@ -7,7 +5,7 @@ import createFlow from './.internal/createFlow.js';
*
* @since 3.0.0
* @category Util
* @param {...(Function|Function[])} [funcs] The functions to invoke.
* @param {Function[]} [funcs] The functions to invoke.
* @returns {Function} Returns the new composite function.
* @see flowRight
* @example
@@ -20,6 +18,22 @@ import createFlow from './.internal/createFlow.js';
* addSquare(1, 2);
* // => 9
*/
const flow = createFlow();
function flow(funcs) {
const length = funcs ? funcs.length : 0;
let index = length;
while (index--) {
if (typeof funcs[index] != 'function') {
throw new TypeError('Expected a function');
}
}
return function(...args) {
let index = 0;
let result = length ? funcs[index].apply(this, args) : args[0];
while (++index < length) {
result = funcs[index].call(this, result);
}
return result;
};
}
export default flow;

View File

@@ -1,4 +1,4 @@
import createFlow from './.internal/createFlow.js';
import flow from './flow.js';
/**
* This method is like `flow` except that it creates a function that
@@ -6,7 +6,7 @@ import createFlow from './.internal/createFlow.js';
*
* @since 3.0.0
* @category Util
* @param {...(Function|Function[])} [funcs] The functions to invoke.
* @param {Function[]} [funcs] The functions to invoke.
* @returns {Function} Returns the new composite function.
* @see flow
* @example
@@ -19,6 +19,8 @@ import createFlow from './.internal/createFlow.js';
* addSquare(1, 2);
* // => 9
*/
const flowRight = createFlow(true);
function flowRight(funcs) {
return flow(funcs.reverse());
}
export default flowRight;