Skip to content

Instantly share code, notes, and snippets.

@haiiro-shimeji
Last active December 17, 2015 13:19
Show Gist options
  • Select an option

  • Save haiiro-shimeji/5616724 to your computer and use it in GitHub Desktop.

Select an option

Save haiiro-shimeji/5616724 to your computer and use it in GitHub Desktop.
#js #tddjs
(function() {
var namespaces = {};
function namespace(string) {
var object = namespaces;
var levels = string.split(".");
if (!(levels[0] in object) && levels[0] in window) {
throw new Error(levels[0] + " is already defined as a global variable.");
}
for (var i in levels) {
if (typeof object[levels[i]] == "undefined") {
object[levels[i]] = {};
}
object = object[levels[i]];
}
window[levels[0]] = namespaces[levels[0]];
return object;
}
window.namespace = namespace;
}())
TestCase("Namespace", {
setUp: function() {
delete window.nstest;
},
"test sounld create non-existent object": function() {
namespace("nstest");
assertObject(nstest);
},
"test error should be thrown when the same as global variable is given": function() {
assertException(namespace.bind(null, "window"), "Error");
},
"test sould not overwite existent objects": function() {
window.nstest = { nested: {} };
var result = namespace("nstest.nested");
assertSame(nstest.nested, result);
},
"test only create missing parts": function() {
var existing = {};
nstest = { nested: { ui: existing } };
var result = namespace("nstest.nested.ui");
assertSame(result, nstest.nested.ui);
assertObject(nstest.nested.ui);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment