Skip to content

Instantly share code, notes, and snippets.

@dSalieri
Created September 20, 2021 08:43
Show Gist options
  • Select an option

  • Save dSalieri/4f76e634249c31b4f5e7582fa0caebdf to your computer and use it in GitHub Desktop.

Select an option

Save dSalieri/4f76e634249c31b4f5e7582fa0caebdf to your computer and use it in GitHub Desktop.
Test on equality of maps
function shallowMapEquality(map1, map2){
if(!(map1 instanceof Map) || !(map2 instanceof Map))
throw Error("One of arguments or both is/are not instance of Map");
if(map1 === map2) return true;
let it1 = map1[Symbol.iterator]();
let it2 = map2[Symbol.iterator]();
while(true){
let {value: v1, done: d1} = it1.next();
let {value: v2, done: d2} = it2.next();
if(d1 === true || d2 === true) {
if(d1 === d2) return true;
else return false
}
if(v1[0] !== v2[0] || v1[1] !== v2[1]) return false;
}
}
/// Test
let map1 = new Map([["one",1],["two",2],["three",3]]);
let map2 = new Map([["one",1],["two",2],["five",5]]);
let map3 = new Map([["one",1],["two",2],["three",3]]);
let map4 = new Map([["one",1],["two",2],["three",3],["four",4]]);
let map5 = new Map([["one",1],["two",2],["3",3]]);
shallowMapEquality(map1, map1); /// true
shallowMapEquality(map1, map2); /// false
shallowMapEquality(map1, map3); /// true
shallowMapEquality(map1, {}); /// Error
shallowMapEquality(map1, map4); /// false
shallowMapEquality(map1, map5); /// false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment