[Type] Array<T>

Part of: mobl
Inherits from: mobl::Object

Represents arrays of of type T. Generally it is recommended to use Collection instead, because Array is not a reactive datastructure, i.e. user interfaces will not react to changes in arrays. Thus,

list(el in someArray) {
   ...
}
button("Add", onclick={ someArray.push(...); })

Won't trigger a re-render of the list.

However, Arrays are more efficient than collections and are also used to interoperate with Javascript APIs.

Instantiation

Arrays can be instantiated in two ways. One is using the Array<T>(...) constructor, the other is [...]. The latter can only be used if one or more elements are provided.

Example:

var ar = [1, 2, 3]; // type of ar: Array<Num>
var ar2 = Array<Num>(); // empty Array<Num>

Syntactic sugar

The type Array<T> can also be written as [T].

Example:

var ar : Array<Num> = [1, 2, 3];
var ar2 : [Num] = [1, 2, 3];

Instance methods

get(n : Num) : T

Returns the n-th item in the array.

Example:

var ar = [1, 2, 3];
ar.get(0) // -> 1

push(item : T) : void

Adds item to the end of the array.

Example:

var ar = [1, 2];
ar.push(3);
ar // -> [1, 2, 3]

join(sep : String) : String

Joins all elements of the array together, separated by sep.

Example:

var ar = [1, 2, 3]
ar.join("|") -> "1|2|3"

map(fn : Function1<T, ?>) : [?]

Applies a function to each element in the array and returns a new array with the function applied to each element.

Example:

var ar = [1, 2, 3];
function sqr(n : Num) : Num {
  return n*n;
}
ar.map(sqr) // -> [1, 4, 9]

filter(fn : Function1<T, Bool>) : [T]

Filters an array based on function fn, returns all elements for which fn returned true.

Example:

var ar = [1, 2, 3, 4];
function isEven(n : Num) : Bool {
  return n % 2 == 0;
}
ar.filter(isEven) // -> [2, 4]

reduce(fn : Function2<T, T, ?>) : ?

Reduces an array to a single value based by applying fn to pairs of two items.

Example:

var ar = [1, 2, 3, 4];
function add(n1 : Num, n2 : Num) : Num {
  return n1 + n2;
}
ar.reduce(add) // -> 10

contains(el : T) : Bool

Returns whether el is in the array.

Example:

var ar = [1, 2, 3];
ar.contains(1) // -> true

splice(idx : Num, numToDelete : Num) : [T]

Used to remove numToDelete items from the array at index idx. Modifies the array in-place.

Example:

var ar = [1, 2, 3];
ar.splice(1, 1);
ar // -> [1, 3]

insert(idx : Num, item : T) : void

Inserts item at index idx.

Example:

var ar = [1, 2, 3];
ar.insert(0, 8);
ar // -> [8, 1, 2, 3];

remove(item : T) : void

Removes item from the array, if it's in.

Example:

var ar = [1, 2, 3];
ar.remove(2);
ar // -> [1, 3];

Instance properties

length : Num

The length of the array.

Example:

var ar = [1, 2, 3]
s.length // -> 3
mobl/array.txt · Last modified: 2013/10/01 02:28 (external edit)