Skip to content

Instantly share code, notes, and snippets.

@Ketcap
Last active August 20, 2018 12:27
Show Gist options
  • Save Ketcap/661653ad5fe0a941732ca0f8e872bfb7 to your computer and use it in GitHub Desktop.
Save Ketcap/661653ad5fe0a941732ca0f8e872bfb7 to your computer and use it in GitHub Desktop.
Anagram
const anagram = (word1, word2) => {
const w1 = word1.toLowerCase().replace(/\s+|!/g, '').split('');
const w2 = word2.toLowerCase().replace(/\s+|!/g, '').split('')
const letters1 = w1.reduce((prev, current, val) => {
if (typeof prev[current] !== 'undefined') {
return { ...prev, [current]: prev[current] + 1 }
}
return { ...prev, [current]: 1 }
}, {})
const letters2 = w2.reduce((prev, current, val) => {
if (typeof prev[current] !== 'undefined') {
return { ...prev, [current]: prev[current] + 1 }
}
return { ...prev, [current]: 1 }
}, {});
const letterCheck = word1.length > word2 ? letters1 : letters2;
return Object.keys(letterCheck).every((val, index) => (
letters2[val] === letters1[val]
));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment