Created
October 25, 2012 16:55
-
-
Save jalcine/3954021 to your computer and use it in GitHub Desktop.
Implementing Namespaces in CoffeeScript and JavaScript
This file contains 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
# Define the global namespace as 'root'. | |
root = module?.parent?.exports ? window | |
### | |
@fn namespace | |
Allows you to implement a namespace of objects to the global namespace. | |
### | |
root.namespace = -> | |
separator = "." | |
base = root | |
for own key, value of arguments[0] | |
components = key.split separator | |
if components.length isnt 1 | |
for component in components | |
if !base[component] | |
base[component] = {} | |
base = base[component] | |
else | |
base[key] = {} | |
base = base[key] | |
for own propertyName, propertyValue of value | |
base[propertyName] = propertyValue | |
base |
This file contains 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 root, _ref, _ref1, | |
__hasProp = {}.hasOwnProperty; | |
root = (_ref = typeof module !== "undefined" && module !== null ? (_ref1 = module.parent) != null ? _ref1.exports : void 0 : void 0) != null ? _ref : window; | |
/* | |
@fn namespace | |
Allows you to implement a namespace of objects to the global namespace. | |
*/ | |
root.namespace = function() { | |
var base, component, components, key, propertyName, propertyValue, separator, value, _i, _len, _ref2; | |
separator = "."; | |
base = root; | |
_ref2 = arguments[0]; | |
for (key in _ref2) { | |
if (!__hasProp.call(_ref2, key)) continue; | |
value = _ref2[key]; | |
components = key.split(separator); | |
if (components.length !== 1) { | |
for (_i = 0, _len = components.length; _i < _len; _i++) { | |
component = components[_i]; | |
if (!base[component]) { | |
base[component] = {}; | |
} | |
base = base[component]; | |
} | |
} else { | |
base[key] = {}; | |
base = base[key]; | |
} | |
for (propertyName in value) { | |
if (!__hasProp.call(value, propertyName)) continue; | |
propertyValue = value[propertyName]; | |
base[propertyName] = propertyValue; | |
} | |
} | |
return base; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment