Created
May 27, 2015 21:58
-
-
Save tylerdmace/fcf8f1f60488959a5fd5 to your computer and use it in GitHub Desktop.
Tree Traversal (Check to see if all values are the same)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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