Check to see if two provided strings are anagrams of each other. One string is an anagram of another if it uses the same characters in the same quantity. Only consider characters, not spaces or punctuation. Consider capital letters to be the same as lower case
anagrams('rail safety', 'fairy tales') --> True
anagrams('RAIL! SAFETY!', 'fairy tales') --> True
anagrams('Hi there', 'Bye there') --> False
Two solutions Use helper function to write DRY code
String.prototype.replace()
, String.prototype.toLowerCase()
, String.prototype.length
Object.keys(obj)
returns an arrayArray.prototype.sort()
methodfunction anagrams(stringA, stringB) {
return cleanString(stringA) === cleanString(stringB);
}
// Helper function
function cleanString(str){
return str.replace(/[^\w]/g, "").toLowerCase().split("").sort().join(""); // remember join()
}
function anagrams(stringA, stringB) {
let charMapA = makeCharMap(stringA);
let charMapB = makeCharMap(stringB);
// Pull out keys from an object
if (Object.keys(charMapA).length !== Object.keys(charMapB).length){
return false;
}
for (let key in charMapA){
if (charMapA[key] !== charMapB[key]){
return false;
}
}
return true;
}
// Helper function
function makeCharMap(str){
let charMap = {};
for (let char of str.replace(/[^\w]/g, "").toLowerCase()){
if (!charMap[char]){
charMap[char] = 1;
} else {
charMap[char]++;
}
}
return charMap;
}
anagrams('rail safety', 'fairy tales')
anagrams('RAIL! SAFETY!', 'fairy tales')
anagrams('Hi there', 'Bye there')