Created
March 1, 2016 18:35
-
-
Save aleclarson/419dd57017cf2cfdb512 to your computer and use it in GitHub Desktop.
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
require "../../../lotus-require" | |
NamedFunction = require "named-function" | |
WeakMap = require "weak-map" | |
Namespace = module.exports = NamedFunction "Namespace", -> | |
return new Namespace unless @ instanceof Namespace | |
@cache = WeakMap() | |
@ | |
Namespace::get = (target, key) -> | |
throw TypeError "'target' must inherit from Object" unless target instanceof Object | |
data = @cache.get target | |
return data unless arguments.hasOwnProperty 1 | |
cake data, key, get: yes if data instanceof Object | |
Namespace::set = (target, key, value) -> | |
throw TypeError "'target' must inherit from Object" unless target instanceof Object | |
return @cache.set target, key unless arguments.hasOwnProperty 2 | |
data = @cache.get target | |
data = @cache.set target, {} unless data instanceof Object | |
cake data, key, set: value | |
Namespace::has = (target, key) -> | |
throw TypeError "'target' must inherit from Object" unless target instanceof Object | |
return @cache.has target unless arguments.hasOwnProperty 1 | |
data = @cache.get target | |
return no unless data instanceof Object | |
cake data, key, has: yes | |
Namespace::remove = (target, key) -> | |
throw TypeError "'target' must inherit from Object" unless target instanceof Object | |
return @cache.remove target unless arguments.hasOwnProperty 1 | |
data = @cache.get target | |
return no unless data instanceof Object | |
cake data, key, remove: yes | |
actions = ["get", "set", "has", "remove"] | |
getAction = (actions, options) -> | |
for action in actions | |
return action if options.hasOwnProperty action | |
throw Error "Missing action. Try: " + actions.join ", " | |
# Follow the crumbs to the cake. | |
cake = (object, key, options) -> | |
action = getAction actions, options | |
crumbs = key.split "." | |
key = crumbs.pop() | |
for crumb in crumbs | |
trail = object[crumb] | |
unless trail instanceof Object | |
switch action | |
when "get" | |
return | |
when "set" | |
trail = object[crumb] = {} | |
when "has" | |
return no | |
when "remove" | |
return no | |
object = trail | |
switch action | |
when "get" | |
object[key] | |
when "set" | |
object[key] = options.set | |
when "has" | |
object.hasOwnProperty key | |
when "remove" | |
delete object[key] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment