javascript compare maps code example
Example 1: javascript map
function listFruits() {
let fruits = ["apple", "cherry", "pear"]
fruits.map((fruit, index) => {
console.log(index, fruit)
})
}
listFruits()
Example 2: javascript map
const numbers = [0,1,2,3];
console.log(numbers.map((number) => {
return number;
}));
Example 3: javascript compare maps
"use strict";
function compareMaps(map1, map2) {
var testVal;
if (map1.size !== map2.size) {
return false;
}
for (var [key, val] of map1) {
testVal = map2.get(key);
if (testVal !== val || (testVal === undefined && !map2.has(key))) {
return false;
}
}
return true;
}
var o = {"k" : 2}
var m1 = new Map();
m1.set("obj", o);
m1.set("str0", undefined);
m1.set("str1", 1);
m1.set("str2", 2);
m1.set("str3", 3);
var m2 = new Map();
m2.set("str0", undefined);
m2.set("obj", o);
m2.set("str1", 1);
m2.set("str2", 2);
m2.set("str3", 3);
log(compareMaps(m1, m2));
m1.set("str-undefined", undefined);
m2.set("str4", 4);
log(compareMaps(m1, m2));
m1.delete("str-undefined");
log(compareMaps(m1, m2));
m1.set("str4", 5);
log(compareMaps(m1, m2));
function log(args) {
var str = "";
for (var i = 0; i < arguments.length; i++) {
if (typeof arguments[i] === "object") {
str += JSON.stringify(arguments[i]);
} else {
str += arguments[i];
}
}
var div = document.createElement("div");
div.innerHTML = str;
var target = log.id ? document.getElementById(log.id) : document.body;
target.appendChild(div);
}