Created
August 8, 2014 14:18
-
-
Save jahan-addison/2b8666cdc2bb3ee9ef96 to your computer and use it in GitHub Desktop.
Category tree ( 'trie' ) to be used with d3's treemap
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
/* | |
Category-tree | |
Search time: O(n) | |
Insert time: O(n) | |
*/ | |
if (!Array.prototype.find) { | |
Object.defineProperty(Array.prototype, 'find', { | |
enumerable: false, | |
configurable: true, | |
writable: true, | |
value: function(predicate) { | |
if (this == null) { | |
throw new TypeError('Array.prototype.find called on null or undefined'); | |
} | |
if (typeof predicate !== 'function') { | |
throw new TypeError('predicate must be a function'); | |
} | |
var list = Object(this); | |
var length = list.length >>> 0; | |
var thisArg = arguments[1]; | |
var value; | |
for (var i = 0; i < length; i++) { | |
if (i in list) { | |
value = list[i]; | |
if (predicate.call(thisArg, value, i, list)) { | |
return value; | |
} | |
} | |
} | |
return undefined; | |
} | |
}); | |
}; | |
var Category_tree = function() { | |
}; | |
Category_tree.prototype = (function() { | |
var tree = {}; | |
tree.children = []; | |
return { | |
Constructor: Category_tree, | |
insert: function(string, category, parent) { | |
if (tree.children.length === 0) { | |
tree.name = category; | |
tree.children.push({data: string}); | |
return; | |
} | |
categoryParent = Category_tree.prototype.find(parent || category); | |
if (typeof parent !== 'undefined') { | |
var exists = false; | |
parent = categoryParent; | |
parent.find(function(e) { | |
if (e.name == category) { | |
exists = true; | |
parent = e; | |
} | |
}); | |
if (!exists) { | |
parent.push({name: category}); | |
parent.find(function(e) { | |
if (e.name == category) { | |
parent = e; | |
} | |
}); | |
} | |
} else { | |
parent = tree; | |
parent.name = category; | |
} | |
if (typeof parent.children == 'undefined') { | |
parent.children = []; | |
} | |
parent.children.push({data: string}); | |
}, | |
toString: function() { | |
return tree; | |
}, | |
find: function(category) { | |
var parent = tree.children, | |
stack = [], | |
found = false; | |
while(1) { | |
parent.find(function(e) { | |
if (e.name == category) { | |
parent = e; | |
found = true; | |
} | |
if (typeof e.children !== 'undefined') { | |
stack.push(e.children); | |
} | |
}); | |
if (stack.length >= 1) { | |
parent = stack.pop(); | |
} else { | |
break; | |
} | |
} | |
return (found) ? parent : tree.children; | |
} | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment