3

In coffee script i have this little code snippet.

class Collection

  construct:(@collection=[])

Now i want to access that object as if it was an array but i want to get the collection variable when i do so. In other languages i would implements an ArrayAccess of some type and code the next, current etc methods

obj= new Collection([1,2,3])

obj[0] # this should equal 1 

How can i do this in javascript or coffeescript either will do

MBehtemam
  • 7,865
  • 15
  • 66
  • 108
Lpc_dark
  • 2,834
  • 7
  • 32
  • 49

1 Answers1

1

That's impossible. You would need some kind of proxy for that. There is no "ArrayAccess" declaration feature, as bracket notation is just property access on your Collection instance (like obj["collection"]).

Instead, you can:

  • implement a getter function, like

    class Collection
      construct:(@collection=[])
      at: (i) ->
        @collection[i]
    
    obj.at 0 # 1
    
  • use the Collection object itself as a holder of the elements (like e.g. jQuery does it). You loose the native array features, though. You might even subclass Array to some extent (.length does not update automatically).

    class Collection
      constructor: (col = []) ->
        @length = 0
        for el in col
          Array::push.call(@, el)
    
    obj[0] # 1
    
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • The at is a good idea. maybe coupled with an all for foreach loops. – Lpc_dark Mar 25 '14 at 06:14
  • 1
    @Lpc_dark: `each` please, `all` is a common synonym for [`every`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every) – Bergi Mar 25 '14 at 14:57