Skip to content

Commit

Permalink
additional argument to map, filter, and forEach; will be passed as `t…
Browse files Browse the repository at this point in the history
…his` to the callback
  • Loading branch information
balpha committed Jun 20, 2011
1 parent 299f890 commit 894e650
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 6 deletions.
12 changes: 6 additions & 6 deletions lyfe.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@
};

var makeForEach_fromFunction = function (f) {
return function (g) {
return function (g, thisObj) {
var index = 0,
gen = {
yield: function (val) { var send = g(val, index, stopIteration); index++; return send; },
yield: function (val) { var send = g.call(thisObj, val, index, stopIteration); index++; return send; },
yieldMany: function (source) { source.forEach(function (val) { gen.yield(val); }) },
stop: stopIteration
};
Expand Down Expand Up @@ -70,12 +70,12 @@
this.forEach(function (val) { result.push(val); });
return result;
},
filter: function (pred) {
filter: function (pred, thisObj) {
var source = this;
return new Generator(function () {
var gen = this;
source.forEach(function (val) {
if (pred(val))
if (pred.call(thisObj, val))
gen.yield(val);
});
});
Expand All @@ -101,12 +101,12 @@
});
});
},
map: function (f) {
map: function (f, thisObj) {
var source = this;
return new Generator(function () {
var gen = this;
source.forEach(function (val) {
gen.yield(f(val));
gen.yield(f.call(thisObj, val));
});
});
},
Expand Down
27 changes: 27 additions & 0 deletions test.html
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,33 @@
var doubled = squares.and(squares).toArray()
return arrEqual(doubled, [1, 9, 25, 1, 9, 25]) && called == 3;
});

test("thisObj argument to filter", function () {
var good1, good2;
var obj = { foo: 123 };
var gen = Generator([42]);
gen.filter(function (x) { good1 = this === window; return true; }).toArray();
gen.filter(function (x) { good2 = this === obj; return true; }, obj).toArray();
return good1 && good2;
});

test("thisObj argument to map", function () {
var good1, good2;
var obj = { foo: 123 };
var gen = Generator([42]);
gen.map(function (x) { good1 = this === window; return 43; }).toArray();
gen.map(function (x) { good2 = this === obj; return 43; }, obj).toArray();
return good1 && good2;
});

test("thisObj argument to forEach", function () {
var good1, good2;
var obj = { foo: 123 };
var gen = Generator([42]);
gen.forEach(function (x) { good1 = this === window; });
gen.forEach(function (x) { good2 = this === obj; }, obj);
return good1 && good2;
});

</script>

Expand Down

0 comments on commit 894e650

Please sign in to comment.