|
4 | 4 | λ.map = function (coll, func) {
|
5 | 5 | var output = [];
|
6 | 6 | for (var index in coll) {
|
7 |
| - output.push(func(coll[index])); |
| 7 | + if (coll.hasOwnProperty(index)) { |
| 8 | + output.push(func(coll[index])); |
| 9 | + } |
8 | 10 | }
|
9 | 11 | return output;
|
10 | 12 | };
|
11 | 13 |
|
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; |
13 | 25 | };
|
| 26 | + |
| 27 | + context.λ = λ; |
| 28 | + context.L = λ; |
14 | 29 | })(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