Last active
December 17, 2015 13:19
-
-
Save haiiro-shimeji/5616724 to your computer and use it in GitHub Desktop.
#js #tddjs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (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; | |
| }()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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