There are several ways to handle a collection of things, such as arrays mentioned in loops and objects.
Objects are versatile data structures. A couple of object types that may be useful are sets and maps.
Each is slightly different, depending on your requirements.
Set Object
set
- store unique values of any type (a value may only occur once)
- not ordered or indexed
- may contain differerent datatypes
Both sets and maps are enclosed in parentheses ( ), but defined and accessed differently.
let myS = new Set([1,3,5,7,9,11]); // a new set initialized with an array
Sprint('"myS" has '+myS.size+' elements<br/>');
Sprint("Does it contain '6'? "+myS.has("6")+"<br/>");
Sprint("How about 5? "+myS.has(5)+"<br/>");
myS.add(14);
for (const item of myS) {
Sprint(item+<br>');
}
Sprint('Any even numbers?<br/>');
for (const item of myS) {
if (item % 2 == 0) {
Sprint('Yep ('+item+')<br/>');
}
A set doesn't have to be initialized with an array - any other iterable object will also work.
Sets are like arrays - they contain a collection of values. A cool thing about sets is they can be used like Venn diagrams (remember them?).
Two sets can be compared to determine if 1 set contains values of another set; or what the difference is between 2 sets; or the combination of both sets, ...
union a new set containing the elements which are in this set, or in the argument set, or in both
difference a new set containing elements which are in this set but not in the argument set
intersection a new set containing the elements which are in this set and in the argument set
symmetric difference a new set containing elements which are in this set or in the argument set, but not in both
subset if all elements in this set is also elements in the argument set
superset if all elements in the argument set are also in this set
disjoint if this set has no elements in common with the argument set
Map Object
There is a map method as well. Don't confuse them.
Map
- like an array, but holds a set of key-value pairs
- indexed by arbitrary 'values' (not necessarily sequential integers)
- fast lookups, no matter how large the map is
A typical use of a Map object might be a list of your friends with their birthdays.
let myFriends=new Map(); // a new, empty map created
myFriends.set("Terry","1955-02-23");
myFriends.set("Tiina","1950-10-12");
myFriends.set("Alia","2017-11-04");
myFriends.set("Frank","1946-12-12)";
Sprint ('I have '+myFriends.size+' friends!')
Sprint ("Tiina's birthday is "+myFriends.get('Tiina'));"
Sprint('My friend Frank passed away.');
myFriends.delete("Frank");
Sprint ('Now I have '+myFriends.size+' friends!');
Sprint("Do I have Janice's birthday? "+ myFriends.has("Janice");
Sprint("I don't want any of these friends anymore");
myFriends.clear();
Sprint ("Sorry folks. I have "+myFriends.size+" friends now!");