JavaScript Scratches

Sets & Maps

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

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, ...

Map Object

There is a map method as well.
Don't confuse them.

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!");