Last active
December 10, 2015 07:28
-
-
Save victusfate/4401625 to your computer and use it in GitHub Desktop.
examples of nested Hashes in coffeescript (javascript objects). nothing quite as elegant as a nested Hash in ruby (can't overload brackets, too dopey to translate this code directly to coffeescript) blk = lambda {|h,k| h[k] = Hash.new(&blk)} x = Hash.new(&blk) x[:la][:li][:lu][:chunky][:bacon][:foo] = "bar"
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
x = | |
la: | |
li : | |
lu: | |
chunky: | |
bacon: | |
foo: 'bar' | |
console.log "x['la']['li']['lu']['chunky']['bacon']['foo'] is ",x['la']['li']['lu']['chunky']['bacon']['foo'] | |
y = { la: { li: { lu: { chunky: { bacon: { foo:'bary' } } } } } } | |
console.log "y['la']['li']['lu']['chunky']['bacon']['foo'] is ",y['la']['li']['lu']['chunky']['bacon']['foo'] | |
Block = (obj,rest...) -> | |
# console.log 'obj',obj | |
# console.log 'rest',rest | |
obj = {} if (typeof obj is "undefined") | |
if rest.length >= 2 | |
key = rest[0] | |
obj[key] = Block(obj[key],rest[1...]...) | |
obj | |
else if rest.length is 1 | |
obj = rest[0] | |
z = Block(z,'la','li','lu','chunky','bacon','foo','barz') | |
console.log z['la']['li']['lu']['chunky']['bacon']['foo'] | |
# >> barz | |
z = Block(z,'la','li','lu','chunky','bacon','fooz','ball') | |
console.log 'z is' | |
console.log JSON.stringify(z) | |
# >> {"la":{"li":{"lu":{"chunky":{"bacon":{"foo":"barz","fooz":"ball"}}}}}} | |
a = z['la']['li']['lu'] | |
a = Block(a,'chunky','bacon','another','node') | |
console.log 'a is' | |
console.log JSON.stringify(a) | |
# >> a is {"chunky":{"bacon":{"foo":"barz","fooz":"ball","another":"node"}}} | |
console.log 'z is' | |
console.log JSON.stringify(z) | |
# >> z is {"la":{"li":{"lu":{"chunky":{"bacon":{"foo":"barz","fooz":"ball","another":"node"}}}}}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment