Hoodfc
1/6/2020 - 8:40 AM

Anagram Frequency Counter

Anagram Frequency Counter

//checks if two strings are anagrams (if they have the same letters with the same frequency within the string)
//I used the frequency pattern as shown is the course JS Algorithms and Data Structures by Colt Steele on Udemy
function validAnagram(str1, str2) {
  let frequencyCounter1 = {};
  let frequencyCounter2 = {};
  if (str1.lenght !== str2.lenght) return false;

  for (let val1 of str1) {
    frequencyCounter[val1] = (frequencyCounter[val1] || 0) + 1;
  }
  for (let val2 of str2) {
    frequencyCounter[val2] = (frequencyCounter[val2] || 0) + 1;
  }

  for (let key of frequencyCounter1) {
    if (!(key in frequencyCounter2)) return false;
    if (frequencyCounter2[key] !== frequencyCounter1[key]) return false;
  }

  return true;
}