DEV Community

Discussion on: Anagrams Checker - Three JavaScript Solutions

Collapse
 
lexlohr profile image
Alex Lohr

My first solution (ES2019) looks like this:

const isAnagram = (word1, word2) => {
    const charsInWord = {};
    const maxLength = Math.max(word1.length, word2.length);
    for (let index = 0; index < maxLength; index++) {
        const char1 = word1.charCodeAt(index);
        const char2 = word2.charCodeAt(index);
        if (char1 >= 97 && char1 <= 122) {
            charsInWord[char1] = (charsInWord[char1] || 0) + 1;
        }
        if (char2 >= 97 && char2 <= 122) {
            charsInWord[char2] = (charsInWord[char2] || 0) - 1;
        }
    }
    return (Object.values(charsInWord) || { a: 0 }).every((charCount) => charCount === 0);
}