Namespace

The simple beauty of http://gist.github.com/303614 ruined in support of added features. This just seems wrong and looks ugly. I should at least cache _create to prevent redefinition each time it's used.

by John Schulz

JavaScript

var something = ns(['bar', 'baz', 'bam'], 'goes.here.now');
ns('then', 'goes.here');
ns('or', goes.here);
ns(['a.one', 'b.two', 'c.three.one', 'c.three.two'], 'new_one');
console.log(something, goes, new_one);

function ns( spaces, root )
{
    var IS_ARRAY = (Object.prototype.toString.call(spaces) === "[object Array]"),
        i = -1, l = spaces.length, space,
        self = this;

    if (!self.create) {
        self.create = function (str, branch)
        {
            var IS_STRING = Object.prototype.toString.call(branch) === '[object String]',
                root = IS_STRING ? self.create(branch) : (branch || window),
                parts = str.split('.'), part,
                ndx = -1, len = parts.length;

            while (++ndx < len) {
                part = parts[ndx];
                if (!(part in root)) root[part] = {};
                root = root[part];
            }

            return root;
        };

    }

    if (IS_ARRAY) {
        while (++i < l) {
            space = self.create(spaces[i], root);
        }
    } else {
        space = self.create(spaces, root);
    }

    return space;
}