@tomegz/MeaslyGrownDanishswedishfarmdog
JavaScript

No description

repl talk
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
function anagramChecker(str1, str2) {
    /* create a Map of "letter: frequency" pairs, ignore space as anagrams
    can have multiple spaces */
    let freq = new Map();
    let currentLetter;
    for(let [i, occur] = [0, 0]; i < str1.length; i++) {
      currentLetter = str1.charAt(i);
      if(currentLetter === " ") continue;
      occur = freq.get(currentLetter) + 1 || 1;
      freq.set(currentLetter, occur);
    }
    /* Loop through second string and decrease the frequencies. 
       If letter is not found in our Map or number drops below 0,
       then we already know the words aren't anagrams */
    for(let [i, occur] = [0, 0]; i < str2.length; i++) {
      currentLetter = str2.charAt(i);
      if(currentLetter === " ") continue;
      occur = freq.get(currentLetter) - 1;
      if(isNaN(occur) || occur < 0) return 0;
      freq.set(currentLetter, occur);
    }
    /* Check if any letter has frequency greater than 0, if true,
       then words are not anagrams, otherwise they are */
    let myArr = [...freq.values()];
    return myArr.some(value => value > 0) ? 0 : 1;
}
console.log(anagramChecker("JIM MORRISON", "MR MOJO RISIN"));
console.log(anagramChecker("JIM MORRISON", "MR MOJO IS IN"));
console.log(anagramChecker("TOM MARVOLO RIDDLE", "I AM LORD VOLDEMORT"));
console.log(anagramChecker("ABAB", "ABBA"));
console.log(anagramChecker("AD", "BC"));
console.log(anagramChecker("AABBCCD", "ABBCCDD"));
Native Browser JavaScript