List Class - CoffeeScript Design Patterns

Posted on

While not a pattern, the List class serves as an integral part of the Iterator pattern and Observer pattern. Because Javascript doesn’t user pointers it gets a little tricky. I manually assign a property called POINTER to objects to serve this purpose. In a normal app the pointer could be a unique ID that already exists on an object. The end result is a sort-of hybrid array/object thing.

[code lang=“coffee”]
class List
constructor: () ->

A list of pointers

@items = [L]

  1. Objects passed in by pointer

@objects = {}

  1. Returns the number of objects in the list

count: () -> @items.length

  1. Returns the object at the given length

get: (index) -> @objects[@items[index]]

  1. Returns the first object in the list

first: () -> @objects[@itemsL0]

  1. Returns the last object in the list

last: () -> @objects[@items[@items.length – 1]]

  1. Adds the argument to the list, making it the last item

append: (item) -> pointer = item.POINTER @items.push pointer @objects[pointer] = item

  1. Removes the given element from the list.

remove: (item) -> pointer = item.POINTER delete @objects[pointer] index = pointer in @items # delete @items[index] if index isnt -1 @items.splice index, 1

  1. Removes the last element from the list

removeLast: () -> @remove @last

  1. Removes the first element from the list

removeFirst: () -> @remove @first

  1. Removes all elements from the list

removeAll: () -> @items = [L] @objects = {}
[/code]

Usage:

[code lang=“coffee”]
list = new List()
list.append POINTER: "uniqueid", other: "properties"
[/code]