JSFiddle - React, Tailwind, and code Playground

by John Schulz

JavaScript

/*
* ns('foo.bar'); 
*   => window.foo = {bar: {} };
* ns('some.arbitrary.depth.string');
*   => window.some = {arbitrary: {depth: {string: {} } };
* ns('some.other.ns');
*   => window.some is already created, so window.some.other = {ns: {}};
*/
function ns (str, root)
{
    var parts = str.split('.'),
        part,
        ndx = 0,
        len = parts.length;
    
    root = root || this;
    
    while (ndx < len ){
        part = parts[ndx];
        if (! (part in root)) root[part] = {};
        root = root[part];
        ndx++;
    }
}

ns('foo.bar'); 
foo.bar = 'baz';
console.log(foo);

ns('some.arbitrary.depth.string');
some.arbitrary.depth.string = "Your string here";
console.log(some);

ns('some.other.ns');
some.other.ns = 'some other value';
console.log(some);