Skip to content

Commit

Permalink
reduce() now too
Browse files Browse the repository at this point in the history
  • Loading branch information
James Halliday committed Feb 18, 2011
1 parent ee52d80 commit c89ae4b
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
11 changes: 11 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,17 @@ Traverse.prototype.forEach = function (cb) {
return this.value;
};

Traverse.prototype.reduce = function (cb, init) {
var skip = arguments.length === 1;
var acc = skip ? this.value : init;
this.forEach(function (x) {
if (!this.isRoot || !skip) {
acc = cb.call(this, acc, x);
}
});
return acc;
};

Traverse.prototype.paths = function () {
var acc = [];
this.forEach(function (x) {
Expand Down
20 changes: 20 additions & 0 deletions test/mutability.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,23 @@ exports.cloneT = function () {
obj.c.push(5);
assert.eql(res.c, [ 3, 4 ]);
};

exports.reduce = function () {
var obj = { a : 1, b : 2, c : [ 3, 4 ] };
var res = Traverse(obj).reduce(function (acc, x) {
if (this.isLeaf) acc.push(x);
return acc;
}, []);
assert.eql(obj, { a : 1, b : 2, c : [ 3, 4 ] });
assert.eql(res, [ 1, 2, 3, 4 ]);
};

exports.reduceInit = function () {
var obj = { a : 1, b : 2, c : [ 3, 4 ] };
var res = Traverse(obj).reduce(function (acc, x) {
if (this.isRoot) assert.fail('got root');
return acc;
});
assert.eql(obj, { a : 1, b : 2, c : [ 3, 4 ] });
assert.eql(res, obj);
};

0 comments on commit c89ae4b

Please sign in to comment.