-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Update "reduce" to allow uncurried call
- Loading branch information
Showing
2 changed files
with
53 additions
and
14 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,25 +1,54 @@ | ||
import { pipe } from "../pipe/pipe" | ||
|
||
const _reduce = (fn, defaultAcc, _source) => { | ||
let acc = defaultAcc | ||
const source = Array.isArray(_source) ? _source : [_source] | ||
|
||
for (let i = 0, length = source.length; i < length; i++) { | ||
acc = Array.isArray(fn) | ||
? pipe(...fn)(acc, source[i], i, source) | ||
: fn(acc, source[i], i, source) | ||
} | ||
|
||
return acc | ||
} | ||
|
||
/** | ||
* Apply a function against an accumulator and each element in the array (from | ||
* left to right) to reduce it to a single value. | ||
* | ||
* @param {Function} fn Reduce function | ||
* @param {Object} defaultAcc The default acc | ||
* @param {Array} source Source input | ||
* @param {Function} fn Reduce function | ||
* @param {Object} defaultAcc Default accumulator value | ||
* @param {Array} source Source input | ||
* | ||
* @return {mixed} | ||
* | ||
* @tag Array | ||
* @signature (fn: Function, defaultAcc: mixed) => (source: Array): mixed | ||
* @signature (fn: Function, defaultAcc: mixed, source: Array): mixed | ||
* | ||
* @example | ||
* const sum = (acc, item) => acc + item | ||
* | ||
* reduce(sum, 0, [1, 2]) | ||
* // => 3 | ||
*/ | ||
const reduce = (fn, defaultAcc) => source => { | ||
let acc = defaultAcc | ||
const sourceArray = Array.isArray(source) ? source : [source] | ||
|
||
for (let i = 0, length = sourceArray.length; i < length; i++) { | ||
acc = fn(acc, sourceArray[i], i, sourceArray) | ||
export const reduce = (...params) => { | ||
/* | ||
* @signature (fn: Fn|Fn[], defaultAcc: mixed) => (source: []): mixed | ||
* | ||
* reduce(sum, 0)([1, 2]) | ||
* // => 3 | ||
*/ | ||
if (params.length < 3) { | ||
return source => _reduce(params[0], params[1], source) | ||
} | ||
|
||
return acc | ||
/* | ||
* @signature (fn: Fn|Fn[], defaultAcc: mixed, source: []): mixed | ||
* | ||
* reduce(sum, 0, [1, 2]) | ||
* // => 3 | ||
*/ | ||
return _reduce(...params) | ||
} | ||
|
||
export { reduce } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters