This repository has been archived by the owner on May 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
Array & Map Constraints
Stephen Oney edited this page Jan 15, 2014
·
7 revisions
So far, all of the constraint variables we have discussed have been simple objects (constructed using cjs.constraint()
. However, constraint variables can also be arrays or objects (maps).
####Arrays
cjs.array(arr)
creates an Array constraint, which adds a constraint wrapper to all of the standard Array.prototype
methods, including .pop()
, .push()
, etc.
It also includes the special methods:
-
.length()
to get the array's length -
.item(index)
to get the item atindex
-
.item(index, val)
to set the item atindex
toval
-
.itemConstraint(index)
to create a constraint whose value is always the array's value atindex
-
.toArray()
converts this array to a JavaScript array
Example:
var arr = cjs.array({
value: [1,2,3]
});
arr.push(4);
arr.length(); // 4
arr.toArray(); // [1,2,3,4]
####Maps
cjs.map(obj)
creates a Map constraint, which adds a constraint wrapper to a standard object with key/value pairs. It contains a number of methods, including:
-
.clear()
to clear every key/value pair -
.keys()
to fetch an array of keys -
.values()
to fetch an array of values -
.forEach(callback)
to loop through every key/value pair -
.has(key)
to check ifkey
is a key in the object -
.item(key)
to get the value associated with keykey
-
.item(key, val)
to set the value associated with keykey
tovalue
-
.remove(key)
to unset the value for keykey
-
.size()
to get the number of entries -
.toObject()
to convert the map to a JavaScript object
Example:
var m = cjs.map({
value: {x: 1, y: 2}
});
m.item('x'); // 1
m.item('z', 3);
m.keys(); // ['x','y','z']