Skip to content

Instantly share code, notes, and snippets.

@eldyvoon
Last active January 3, 2018 04:58
Show Gist options
  • Save eldyvoon/c6e423fa831cc4692771f2eada7f96ab to your computer and use it in GitHub Desktop.
Save eldyvoon/c6e423fa831cc4692771f2eada7f96ab to your computer and use it in GitHub Desktop.
Anagrams in JavaScript
//specs
anagrams('rail safety', 'fairy tales') // true
anagrams('RAIL SAFETY', 'fairy tales') // true
anagrams('hi there', 'bye there') // false
//solution 1
function anagrams(strA, strB) {
const charMapA = buildCharMap(strA);
const charMapB = buildCharMap(strB);
if (Object.keys(charMapA).length !== Object.keys(charMapB).length) {
return false;
}
for (let char in charMapA) {
if (charMapA[char] !== charMapB[char]) {
return false;
}
}
return true;
}
function buildCharMap(str) {
const charMap = {};
for (let char of str.replace(/[^\w]/g,'')) {
charMap[char] = charMap[char] + 1 || 1;
}
return charMap;
}
//solution 2
function anagrams(strA, strB) {
return cleanString(strA) === cleanString(strB);
}
function cleanString(str) {
return str.replace(/[^\w]/g,'').toLowerCase().split('').sort().join('');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment