Skip to content

Commit

Permalink
Should be able to stop traversing when removing or deleting
Browse files Browse the repository at this point in the history
  • Loading branch information
karlbohlmark committed Oct 13, 2011
1 parent 9d4d4c5 commit 4aa61ef
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 2 deletions.
6 changes: 4 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,16 +122,18 @@ function walk (root, cb, immutable) {
state.node = x;
if (stopHere) keepGoing = false;
},
'delete' : function () {
'delete' : function (stopHere) {
delete state.parent.node[state.key];
if (stopHere) keepGoing = false;
},
remove : function () {
remove : function (stopHere) {
if (Array_isArray(state.parent.node)) {
state.parent.node.splice(state.key, 1);
}
else {
delete state.parent.node[state.key];
}
if (stopHere) keepGoing = false;
},
keys : null,
before : function (f) { modifiers.before = f },
Expand Down
48 changes: 48 additions & 0 deletions test/mutability.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,30 @@ exports.remove = function () {
assert.deepEqual(obj, { a : 1, c : [ 3 ] });
};

exports.removeNoStop = function() {
var obj = { a : 1, b : 2, c : { d: 3, e: 4 } };

var keysWithoutStop = [];
Traverse(obj).forEach(function (x) {
keysWithoutStop.push(this.key)
if (this.key == 'c') this.remove();
});

assert.deepEqual(keysWithoutStop, [undefined, 'a', 'b', 'c', 'd', 'e'])
}

exports.removeStop = function() {
var obj = { a : 1, b : 2, c : { d: 3, e: 4 } };

var keys = [];
Traverse(obj).forEach(function (x) {
keys.push(this.key)
if (this.key == 'c') this.remove(true);
});

assert.deepEqual(keys, [undefined, 'a', 'b', 'c'])
}

exports.removeMap = function () {
var obj = { a : 1, b : 2, c : [ 3, 4 ] };
var res = Traverse(obj).map(function (x) {
Expand Down Expand Up @@ -126,6 +150,30 @@ exports.delete = function () {
));
};

exports.deleteNoStop = function() {
var obj = { a : 1, b : 2, c : { d: 3, e: 4 } };

var keys = [];
Traverse(obj).forEach(function (x) {
keys.push(this.key)
if (this.key == 'c') this.delete();
});

assert.deepEqual(keys, [undefined, 'a', 'b', 'c', 'd', 'e'])
}

exports.deleteStop = function() {
var obj = { a : 1, b : 2, c : { d: 3, e: 4 } };

var keys = [];
Traverse(obj).forEach(function (x) {
keys.push(this.key)
if (this.key == 'c') this.delete(true);
});

assert.deepEqual(keys, [undefined, 'a', 'b', 'c'])
}

exports.deleteRedux = function () {
var obj = { a : 1, b : 2, c : [ 3, 4, 5 ] };
Traverse(obj).forEach(function (x) {
Expand Down

0 comments on commit 4aa61ef

Please sign in to comment.