Skip to content

Commit aeac974

Browse files
committed
Implement reduce and fix map.
1 parent f39bad9 commit aeac974

File tree

1 file changed

+46
-2
lines changed

1 file changed

+46
-2
lines changed

js/lambda.js

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,55 @@
44
λ.map = function (coll, func) {
55
var output = [];
66
for (var index in coll) {
7-
output.push(func(coll[index]));
7+
if (coll.hasOwnProperty(index)) {
8+
output.push(func(coll[index]));
9+
}
810
}
911
return output;
1012
};
1113

12-
λ.reduce = function (coll, func) {
14+
λ.reduce = function (coll, func, memo) {
15+
for (var index in coll) {
16+
if (coll.hasOwnProperty(index)) {
17+
if (memo === undefined) {
18+
memo = coll[index];
19+
} else {
20+
memo = func(memo, coll[index], index);
21+
}
22+
}
23+
}
24+
return memo;
1325
};
26+
27+
context.λ = λ;
28+
context.L = λ;
1429
})(this);
30+
31+
32+
var inc = function (v) {
33+
return v + 1;
34+
};
35+
36+
var product = function (pro, next) {
37+
return pro * next;
38+
};
39+
40+
41+
assert(equalToString(λ.map([1,2,3], inc), [2,3,4]), "Mappin'");
42+
assert(equal(λ.reduce([2,3,4], product), 24), "Reducin'");
43+
assert(equal(λ.reduce([2,3,4], product, 3), 72), "Reducin' with memo");
44+
45+
function equal(v1, v2) {
46+
return v1 === v2;
47+
}
48+
49+
function equalToString(v1, v2) {
50+
return v1.toString() === v2.toString();
51+
}
52+
function assert(value, message) {
53+
if (!value) {
54+
throw "FAILED: " + message;
55+
} else {
56+
console.log(message + " works!");
57+
}
58+
}

0 commit comments

Comments
 (0)