Maps are a type of collection available on Coco. Maps contain are made up of key-value pairs. Each key in the map must be unique and can be mapped to a single value only.
make(Map[U64]String)
The make
command can be used to initialize an empty map.
memory mp2 = Map[U64]String{3: "No", 4: "Yes"}
Here the mp2 variable is initialized with a set of key-value pairs using the syntax shown.
The len
operator can be used to get total number of keys present in a map.
joined = merge(mp, mp2)
Maps can be merged using the merge operator. If the keys overlap, the second map pairs overwrite the first. With this operation joined will contain union of all keys present in ‘mp’ and ‘mp2’.
To remove a key/value from the map, one can use remove
function. It doesn’t return the removed value, if we try to remove a non-existent key, remove
doesn’t do anything.
When a collection (map or array) is empty, sweep
can be used to completely remove the empty map from the storage.
Membership check with ?
operator
To check if a map has an element at some key, one can use the “has” operator ?
that returns a boolean “true” if the element exists.
memory exists = m["hi"]?
generate
micro keyword
generate
keyword in front an expression, reading from maps, assures the default value is returned if the key is missing. The case to use generate keyword is e.g.:
counter[newUserId]++
// the above is actually
// counter[newUserId] = counter[newUserId] + 1
// so it returns a runtime error when newUserId
// key doesn't exist
// so we'd need to write
if !counter[newUserId]?:
counter[newUserId] = 0
counter[newUserId]++
With generate, we can resolve the above in a single line:
generate counter[newUserId]++
coco Maps
endpoint invoke Test1()->(output1 Map[String]U64, output2 Map[String]U64, length U256, joined Map[U64]String):
memory mp = make(Map[U64]String)
mp[1] = "Hello"
mp[2] = "Hi"
memory mp2 = Map[U64]String{3: "No", 4: "Yes", 5:"Wrong"}
remove(mp2, 5) // removes the key/value 5:Wrong
length = len(mp)
joined = merge(mp, mp2)
return (output1: mp, output2: mp2, length:length, joined:joined)
coco CleanMap
state persistent:
Operators Map[U64]Operator
class Operator:
field Identifier String
field Guardians []String
endpoint deploy Init(moid String):
mutate operators <- atomic.Operators:
disperse operators[0] <- Operator{
Identifier: moid,
Guardians: make([]String, 0),
}
endpoint invoke persistent Cleanup():
mutate operators <- atomic.Operators:
remove(operators, 0)
sweep(operators)