/
reduceWhile.js
43 lines (41 loc) · 1.57 KB
/
reduceWhile.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import _curryN from './internal/_curryN.js';
import _xReduce from './internal/_xReduce.js';
import _xwrap from './internal/_xwrap.js';
import _reduced from './internal/_reduced.js';
/**
* Like [`reduce`](#reduce), `reduceWhile` returns a single item by iterating
* through the list, successively calling the iterator function. `reduceWhile`
* also takes a predicate that is evaluated before each step. If the predicate
* returns `false`, it "short-circuits" the iteration and returns the current
* value of the accumulator. `reduceWhile` may alternatively be short-circuited
* via [`reduced`](#reduced).
*
* @func
* @memberOf R
* @since v0.22.0
* @category List
* @sig ((a, b) -> Boolean) -> ((a, b) -> a) -> a -> [b] -> a
* @param {Function} pred The predicate. It is passed the accumulator and the
* current element.
* @param {Function} fn The iterator function. Receives two values, the
* accumulator and the current element.
* @param {*} a The accumulator value.
* @param {Array} list The list to iterate over.
* @return {*} The final, accumulated value.
* @see R.reduce, R.reduced
* @example
*
* const isOdd = (acc, x) => x % 2 !== 0;
* const xs = [1, 3, 5, 60, 777, 800];
* R.reduceWhile(isOdd, R.add, 0, xs); //=> 9
*
* const ys = [2, 4, 6]
* R.reduceWhile(isOdd, R.add, 111, ys); //=> 111
*/
var reduceWhile = _curryN(4, [], function _reduceWhile(pred, fn, a, list) {
var xf = _xwrap(function(acc, x) {
return pred(acc, x) ? fn(acc, x) : _reduced(acc);
});
return _xReduce(xf, a, list);
});
export default reduceWhile;