Skip to content

Commit

Permalink
clone in the constructor so updates don't mess up the root object's refs
Browse files Browse the repository at this point in the history
  • Loading branch information
James Halliday committed Jul 28, 2010
1 parent d0f50e9 commit fc5903b
Showing 1 changed file with 19 additions and 4 deletions.
23 changes: 19 additions & 4 deletions traverse.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,23 @@
module.exports = Traverse;
module.exports.Traverse = Traverse;

function Traverse (obj) {
if (!(this instanceof Traverse)) return new Traverse(obj);
function Traverse (refObj) {
if (!(this instanceof Traverse)) return new Traverse(refObj);

// clone refObj for a properly immutable interface:
function clone(ref) {
if (typeof ref == 'object' && ref !== null) {
var node = ref.constructor();
Object.keys(ref).forEach(function (key) {
node[key] = clone(ref[key]);
});
return node;
}
else {
return ref;
}
}
var obj = clone(refObj);

this.get = function () { return obj };

Expand Down Expand Up @@ -30,7 +45,7 @@ function Traverse (obj) {
},
level : path.length,
};
if (typeof(node) == 'object' && node !== null) {
if (typeof node == 'object' && node !== null) {
state.isLeaf = Object.keys(node).length == 0
}
else {
Expand All @@ -41,7 +56,7 @@ function Traverse (obj) {
state.notRoot = !state.isRoot;

f.call(state, node);
if (typeof(state.node) == 'object' && state.node !== null) {
if (typeof state.node == 'object' && state.node !== null) {
parents.push(state);
Object.keys(state.node).forEach(function (key) {
path.push(key);
Expand Down

0 comments on commit fc5903b

Please sign in to comment.