Skip to content

Commit

Permalink
allow setting of keys (ordering) in before modifier
Browse files Browse the repository at this point in the history
  • Loading branch information
benatkin committed Jul 20, 2011
1 parent c74a7ea commit 9fb8e2c
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
3 changes: 2 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,7 @@ function walk (root, cb, immutable) {
// use return values to update if defined
var ret = cb.call(state, state.node);
if (ret !== undefined && state.update) state.update(ret);
state.keys = null;
if (modifiers.before) modifiers.before.call(state, state.node);

if (!keepGoing) return state;
Expand All @@ -261,7 +262,7 @@ function walk (root, cb, immutable) {
&& state.node !== null && !state.circular) {
parents.push(state);

var keys = Object.keys(state.node);
var keys = state.keys || Object.keys(state.node);
keys.forEach(function (key, i) {
path.push(key);

Expand Down
30 changes: 30 additions & 0 deletions test/keys.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
var assert = require('assert');
var Traverse = require('traverse');

exports['sort test'] = function () {
var acc = [];
Traverse({
a: 30,
b: 22,
id: 9
}).forEach(function (node) {
if ((! Array.isArray(node)) && typeof node === 'object') {
this.before(function(node) {
this.keys = Object.keys(node);
this.keys.sort(function(a, b) {
a = [a === "id" ? 0 : 1, a];
b = [b === "id" ? 0 : 1, b];
return a < b ? -1 : a > b ? 1 : 0;
});
});
}
if (this.isLeaf) acc.push(node);
});

assert.equal(
acc.join(' '),
'9 30 22',
'Traversal in a custom order'
);
};

0 comments on commit 9fb8e2c

Please sign in to comment.