forked from jamesshore/lets_code_javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreduce.js
More file actions
85 lines (75 loc) · 1.81 KB
/
reduce.js
File metadata and controls
85 lines (75 loc) · 1.81 KB
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 reduce = require('../');
var test = require('tape');
test('numeric reduces', function (t) {
t.plan(6);
var xs = [ 1, 2, 3, 4 ];
t.equal(
reduce(xs, function (acc, x) { return acc + x }, 0),
10
);
t.equal(
reduce(xs, function (acc, x) { return acc + x }, 100),
110
);
t.equal(
reduce(xs, function (acc, x) { return acc + x }),
10
);
var ys = cripple([ 1, 2, 3, 4 ]);
t.equal(
reduce(ys, function (acc, x) { return acc + x }, 0),
10
);
t.equal(
reduce(ys, function (acc, x) { return acc + x }, 100),
110
);
t.equal(
reduce(ys, function (acc, x) { return acc + x }),
10
);
});
test('holes', function (t) {
t.plan(4);
var xs = Array(10);
xs[2] = 5; xs[4] = 6; xs[8] = 4;
t.equal(
reduce(xs, function (acc, x) { return acc + x }),
15
);
t.equal(
reduce(xs, function (acc, x) { return acc + x }, 100),
115
);
var ys = cripple(Array(10));
ys[2] = 5; ys[4] = 6; ys[8] = 4;
t.equal(
reduce(ys, function (acc, x) { return acc + x }),
15
);
t.equal(
reduce(ys, function (acc, x) { return acc + x }, 100),
115
);
});
test('object', function (t) {
t.plan(1);
var obj = { a: 3, b: 4, c: 5 };
var res = reduce(objectKeys(obj), function (acc, key) {
acc[key.toUpperCase()] = obj[key] * 111;
return acc;
}, {});
t.deepEqual(res, { A: 333, B: 444, C: 555 });
});
function cripple (xs) {
xs.reduce = undefined;
return xs;
}
var objectKeys = function (obj) {
var keys = [];
for (var key in obj) {
if (hasOwn.call(obj, key)) keys.push(key);
}
return keys;
};
var hasOwn = Object.prototype.hasOwnProperty;