Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@victusfate
Last active December 10, 2015 07:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save victusfate/4401625 to your computer and use it in GitHub Desktop.
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"
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