Created
February 6, 2018 02:03
-
-
Save Reizinixc/e62dd639964d6a4685f16629efb07a7a to your computer and use it in GitHub Desktop.
Namespace generator for JavaScript using in website. Cut from the work project.
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
var namespace = (function (global) { | |
'use strict'; | |
const separator = '.'; | |
// Inner namespace class for containing the inner namespaces and values. | |
function Namespace() { | |
} | |
return function (namespace) { | |
const chunks = namespace.split(separator); | |
var lastObjRef = global; | |
for (let i = 0; i < chunks.length; ++i) { | |
const chunk = chunks[i]; | |
if (typeof lastObjRef[chunk] === 'undefined') { | |
lastObjRef[chunk] = new Namespace(); | |
} else if (lastObjRef[chunk] instanceof Namespace !== true) { | |
throw new Error(`Namespace '${chunks.slice(0, i + 1).join(separator)}' has been used for storing value.`); | |
} | |
lastObjRef = lastObjRef[chunk]; | |
} | |
return lastObjRef; | |
}; | |
}(window)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment