Recursive word tree

Recursive function to create a nested word tree.

by Augustus Yuan

JavaScript

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;
    }

}