Skip to content

Instantly share code, notes, and snippets.

@tylerdmace
Created May 27, 2015 21:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tylerdmace/fcf8f1f60488959a5fd5 to your computer and use it in GitHub Desktop.
Save tylerdmace/fcf8f1f60488959a5fd5 to your computer and use it in GitHub Desktop.
Tree Traversal (Check to see if all values are the same)
var tree = {
a: 1,
b: 1,
c: 1,
d: {
d1: 1,
d2: 1,
d3: 1
},
e: 1,
f: {
f1: 1,
f2: 1,
f3: 1,
f4: {
f41: 1,
f42: 1,
f43: 1,
f44: 1
}
}
};
var firstSeen, difference = false;
function compare(value) {
if(firstSeen !== undefined) {
if(firstSeen !== value) difference = true;
} else { firstSeen = value; }
}
function treeTraversal(tree, applyFunction) {
for(var i in tree) {
if(tree[i] !== null && typeof tree[i] === 'object') {
treeTraversal(tree[i], compare);
} else {
applyFunction.apply(this, [tree[i]]);
}
if(difference) return true;
}
return false;
}
if(treeTraversal(tree, compare)) console.log('Oops! Data is different, yo!');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment