Arrays, Lists, and Maps - mfichman/jogo GitHub Wiki

Arrays

Basic data structures are built-ins with literal syntax. The simplest is the Array class:

array = ["one", "two", "three"]
one = array[0]
array[1] = "four"

This array actually an array of Strings, so it's real type is Array[String]. Here is a list of useful array operations:

a.concat(b)       Concatenate a and b
a.slice(i1, i2)   Returns the sub-array starting with i1 and ending at i2
a.push(e)         Append element e to array a
a.pop()           Remove and return the last element of array a
a.shift(e)        Prepend element e to array a
a.unshift()       Remove and return the first element of array a
a.sort()          Sorts the array in-place
a.length          Returns the length of a

There are many other useful functions listed in the Array documentation.

Maps

Maps, or associative arrays, also have convenient literal syntax:

map = { one: 1, two: 2, three: 3 }
one = map["one"]
map["one"] = four

Sets

Special syntax for sets is as follows:

set = { 1, 2, 3 }
set.contains?(1)
set.remove(1)

Other data structures

Other data structures are also available if needed. For example, while maps have a hash-table based implementation by default, a tree implementation can also be selected:

map TreeMap = { one: 1, two: 2, three: 3}

Notice that you have to tell the compiler the type of collection wanted by annotating the map variable. A similar syntax can be used to construct a linked list rather than an array:

list LinkedList = [ 1, 2, 3 ]

Here is a list of all the collection types implemented in the core language:

TreeMap       RB-tree map implementation.
Hash          Hash table-based map implementation (default).
Array         Dynamically resizable array (default).
List          Doubly-linked list.
TreeSet       RB-tree set implementation.
HashSet       Hash table-based set implementation (default).

All collections support iterators. Sequential collections (Array, List, TreeSet, HashSet) can be iterated by value, and associative collections (HashMap, TreeMap) are iterated by key-value pair. The for loop is most often used to iterate over collections:

for element in array {
    ...
}
for key, value in map {
    ...
}