Created
October 8, 2012 21:01
-
-
Save isaksky/3854955 to your computer and use it in GitHub Desktop.
set/access multiple keys
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
update_in = (obj, keys, value) -> | |
node = obj | |
while true | |
key = keys.shift() | |
if keys.length > 0 | |
node[key] = {} unless node[key]? | |
node = node[key] | |
else | |
node[key] = value | |
break | |
obj | |
# Look up multiple nested keys | |
# For example, get_in({a:{b:99}}, ["a", "b"]) => 99 | |
get_in = (obj, keys, deflt = null) -> | |
x = null | |
node = obj | |
while true | |
key = keys.shift() | |
if keys.length > 0 | |
node = node[key] | |
return deflt unless node? | |
else | |
x = node[key] | |
break | |
if x? then x else deflt |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment