Skip to content

Instantly share code, notes, and snippets.

@Reizinixc
Created February 6, 2018 02:03
Show Gist options
  • Save Reizinixc/e62dd639964d6a4685f16629efb07a7a to your computer and use it in GitHub Desktop.
Save Reizinixc/e62dd639964d6a4685f16629efb07a7a to your computer and use it in GitHub Desktop.
Namespace generator for JavaScript using in website. Cut from the work project.
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