Problem Description
An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. For example, "listen" is an anagram of "silent".
Write a function isAnagram(str1, str2) that takes two strings and returns true if the second string is an anagram of the first, and false otherwise.
Like before, the comparison should be case-insensitive.
Spaces and punctuation should be considered, so
"Dormitory"is an anagram of"dirty room", but you'll need to remove the space.
Test cases:
isAnagram("anagram", "nagaram")should returntrueisAnagram("rat", "car")should returnfalseisAnagram("Dormitory", "dirty room")should returntrue
💡 The 'Syntax Nudge'
You could solve this by sanitizing and sorting the strings, but let's try a more performant approach that doesn't require sorting. This introduces the Frequency Counter pattern.
The core idea is to count how many times each character appears in the first string, and then see if the second string matches that count exactly. An object {} is the perfect tool for this.
I suggest you research:
How to loop through a string using a for ... of loop.
How to add and access properties in a JavaScript object (e.g.,
myObject[key]).A clever trick for incrementing a count in an object:
charMap[char] = (charMap[char] || 0) + 1;. Think about why the|| 0part is necessary.