forked from ramda/ramda
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreduce.js
85 lines (71 loc) · 2.42 KB
/
reduce.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
var R = require('../source/index.js');
var eq = require('./shared/eq.js');
describe('reduce', function() {
var add = function(a, b) {return a + b;};
var mult = function(a, b) {return a * b;};
it('folds simple functions over arrays with the supplied accumulator', function() {
eq(R.reduce(add, 0, [1, 2, 3, 4]), 10);
eq(R.reduce(mult, 1, [1, 2, 3, 4]), 24);
});
it('dispatches to objects that implement `reduce`', function() {
var obj = {x: [1, 2, 3], reduce: function() { return 'override'; }};
eq(R.reduce(add, 0, obj), 'override');
eq(R.reduce(add, 10, obj), 'override');
});
it('returns the accumulator for an empty array', function() {
eq(R.reduce(add, 0, []), 0);
eq(R.reduce(mult, 1, []), 1);
eq(R.reduce(R.concat, [], []), []);
});
it('returns the accumulator for an null/undefined list', function() {
eq(R.reduce(add, 0, null), 0);
eq(R.reduce(R.concat, [], null), []);
eq(R.reduce(add, 0, undefined), 0);
eq(R.reduce(R.concat, [], undefined), []);
});
it('Prefers the use of the iterator of an object over reduce (and handles short-circuits)', function() {
var symIterator = (typeof Symbol !== 'undefined') ? Symbol.iterator : '@@iterator';
function Reducible(arr) {
this.arr = arr;
}
Reducible.prototype.reduce = function(f, init) {
var acc = init;
for (var i = 0; i < this.arr.length; i += 1) {
acc = f(acc, this.arr[i]);
}
return acc;
};
Reducible.prototype[symIterator] = function() {
var a = this.arr;
return {
_pos: 0,
next: function() {
if (this._pos < a.length) {
var v = a[this._pos];
this._pos += 1;
return {
value: v,
done: false
};
} else {
return {
done: true
};
}
}
};
};
var xf = R.take(2);
var apendingT = { };
apendingT['@@transducer/result'] = R.identity;
apendingT['@@transducer/step'] = R.flip(R.append);
var rfn = xf(apendingT);
var list = new Reducible([1, 2, 3, 4, 5, 6]);
eq(R.reduce(rfn, [], list), [1, 2]);
});
it('short circuits with reduced', function() {
var addWithMaxOf10 = function(acc, val) {return acc + val > 10 ? R.reduced(acc) : acc + val;};
eq(R.reduce(addWithMaxOf10, 0, [1, 2, 3, 4]), 10);
eq(R.reduce(addWithMaxOf10, 0, [2, 4, 6, 8]), 6);
});
});