Last active
January 3, 2018 04:58
-
-
Save eldyvoon/c6e423fa831cc4692771f2eada7f96ab to your computer and use it in GitHub Desktop.
Anagrams in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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