Search code examples
javascripthashmapkeyvaluepair

How to implement Java's HashMap.equals(HashMap) in JavaScript


I am trying to write a function that takes two strings and returns whether or not they have the same frequency of letters. It is assumed that neither string is null.

Here is my Java implementation:

  public void addToMap(HashMap<String, Integer> map, String s){
  if(map.get(s) == null){
    map.put(s, 1);
  } else{
    map.put(s, map.get(s)+1);
  }
}

  public boolean perm(String a, String b){
    if(a.length() != b.length()){
      return false;
    }
    HashMap<String, Integer> aMap = new HashMap<>();
    HashMap<String, Integer> bMap = new HashMap<>();
    for(int i = 0; i < a.length(); i++){
      addToMap(aMap, a.substring(i,i+1));
      addToMap(bMap, b.substring(i,i+1));
    }
    return aMap.equals(bMap);
  }

I am trying to replicate this in JavaScript:

const addToMap = (map, s) => {
  if(map[s] == null){
    map[s] = 1;
  } else{
    map[s] = map[s]+1;
  }
}

const perm = (a,b) => {
  if(a.length != b.length){
    return false;
  }
  let aMap = new Map();
  let bMap = new Map();
  for(let i = 0; i < a.length; i++){
    addToMap(aMap, a.substring(i,i+1));
    addToMap(bMap, b.substring(i,i+1));
  }
  return aMap === bMap;
}

I tested perm("abca", "bcaa") for both implementations. The Java code returns true, which is correct. However, the JS functions return false.

Is there a way to return that two maps are equal in JS when they have the same keys and values, but in a different order?


Solution

  • Here is the code that I created that works:

    const addToMap = (map, s) => {
      if(map.has(s)){
        map.set(s, map.get(s)+1);
      } else{ map.set(s, 1);}
    }
    
    const perm = (a, b) => {
      if(a.length != b.length){ return false; }
      let aMap = new Map();
      let bMap = new Map();
      for(let i = 0; i < a.length; i++){
        addToMap(aMap, a.substring(i, i+1));
        addToMap(bMap, b.substring(i, i+1));
      }
      return aMap.toString() == bMap.toString();
    }
    const s1 = "abcda";
    const s2 = "cdbaa";
    console.log(perm(s1, s1));
    

    What happened is I was using the wrong syntax for Map(). I was using bracket notation to create my key value pairs instead or Map.prototype methods.

    See this code sample:

    let m = new Map();
    m.set(1, "a");
    m[2] = "b";
    console.log(m);
    //Output: Map { 1 => 'a', 2: 'b' }
    

    Using the Map.get and Map.set methods works for me.