var tree = {};
var aTree = addToMap(tree, "hack");
console.log(JSON.stringify(aTree));
// tree built upon old tree
var anotherTree = addToMap(aTree, "blargh");
console.log(JSON.stringify(anotherTree));
var andAnotherTree = addToMap(aTree, "hackerz");
console.log(JSON.stringify(andAnotherTree));
// created a nested word tree so we can dig in
function addToMap(tree, string) {
// if the character is in the string, lets dig in
if (string.length === 0) {
return tree;
}
if (tree[string[0]]) {
//console.log('key exists so just dig in');
if (Object.keys(tree[string[0]]).length === 0) {
console.log('if key exists but empty object, we must assign and keep digging');
tree[string[0]] = addToMap(tree[string[0]], string.substr(1));
} else {
tree[string[0]][addToMap(tree[string[0]], string.substr(1))];
}
return tree;
} else {
//console.log('key does not exist so create object');
tree[string[0]] = {};
tree[string[0]] = addToMap(tree[string[0]], string.substr(1));
return tree;
}
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.