Reputation: 18589
I'm trying to do something like this with coffescript
, but it isn't working ..
locations =
[59.32522, 18.07002]
[59.327383, 18.06747]
Upvotes: 3
Views: 93
Reputation: 4646
I realize you found a solution for your own question, and this is not exactly the precise answer you're looking for Kirk. But in Ruby there's an arbitrary hash of hashes object that I'm fond of (note they are more memory intensive than a fixed dimensional array).
blk = lambda {|h,k| h[k] = Hash.new(&blk)}
x = Hash.new(&blk)
x[:la][:li][:lu][:chunky][:bacon][:foo] = "bar"
What's interesting about this structure is that you can use it create any sort of nested hash you need on the fly (kinda like making subdirectories as you go with mkdir -p ). It share's some qualities with JSON objects.
Let's see what a similar object would look like in CoffeeScript
x =
la:
li:
lu:
chunky:
bacon:
foo: 'bar'
alert x['la']['li']['lu']['chunky']['bacon']['foo']
y = { la: { li: { lu: { chunky: { bacon: { foo:'bary' } } } } } }
alert y['la']['li']['lu']['chunky']['bacon']['foo']
I haven't been able to come up with a cleaner create as you go interface than pure JSON object creation since bracket operators can't be overloaded in Javascript
Ok, I came up with a slight abbreviation to the JSON syntax, but it's not as nice as the Ruby nestedHash.
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 = new Block(z,'la','li','lu','chunky','bacon','foo','barz')
console.log z['la']['li']['lu']['chunky']['bacon']['foo']
# extend the object
z = new Block(z,'la','li','lu','chunky','bacon','fooz','ball')
console.log JSON.stringify(z)
# add a node to an internal hash
a = z['la']['li']['lu']
a = new Block(a,'chunky','bacon','another','node')
console.log 'a is',JSON.stringify(a)
# the node now exists on the parent as well
console.log 'z is',JSON.stringify(z)
Upvotes: 1
Reputation: 18589
Oh, I figured it out ..
locations = [
[59.32522, 18.07002]
[59.327383, 18.06747]
]
Upvotes: 2