Skip to content

Instantly share code, notes, and snippets.

@Luke-Rogerson
Created December 16, 2018 18:30
Show Gist options
  • Save Luke-Rogerson/eff3c06c6e4c26d7951b89c87151677f to your computer and use it in GitHub Desktop.
Save Luke-Rogerson/eff3c06c6e4c26d7951b89c87151677f to your computer and use it in GitHub Desktop.
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
function anagrams(stringA, stringB) {
return cleanString(stringA) === cleanString(stringB);
}
function cleanString(str) {
return str
.replace(/[^\w]/g, '')
.toLowerCase()
.split('')
.sort()
.join('');
}
// OR
// function anagrams(stringA, stringB) {
// const mappedStringA = buildCharMap(stringA);
// const mappedStringB = buildCharMap(stringB);
// if (Object.keys(mappedStringA).length !== Object.keys(mappedStringB).length)
// return false;
// for (let char in mappedStringA) {
// if (mappedStringA[char] !== mappedStringB[char]) {
// return false;
// }
// }
// return true;
// }
// function buildCharMap(str) {
// const charMap = {};
// for (char of str.replace(/[^\w]/g, "").toLowerCase()) {
// charMap[char] = charMap[char] + 1 || 1;
// }
// return charMap;
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment