Instantly share code, notes, and snippets.

Embed
What would you like to do?
No `sort()` anagram tester
// Takes two strings.
// Returns true if they're anagrams, false if not.
function isAnagram (a, b) {
const remove = (string, pattern) => string.replace(new RegExp(pattern, 'ig'), '');
// Discard whitespace; anagrams can be different numbers of words
let lettersA = remove(a, '\\s');
let lettersB = remove(b, '\\s');
while (lettersA.length && lettersA.length === lettersB.length) {
const letter = lettersA[0];
lettersA = remove(lettersA, letter);
lettersB = remove(lettersB, letter);
}
return lettersA === lettersB;
}
@robwierzbowski

This comment has been minimized.

Show comment
Hide comment
@robwierzbowski

robwierzbowski Nov 14, 2017

Fun coding exercise suggested by Lara Schenck on Twitter: https://twitter.com/laras126/status/929780884835745792.

How my solution works:

  1. Remove all whitespace. Anagrams can be different numbers of words.
  2. Loop!
    1. If either string is empty or they're not equal length, exit the while loop.
    2. Remove all instances of the first letter in lettersA from both strings. Repeat the loop.
  3. Compare strings. If the words are anagrams, both will be '', an empty string.
Owner

robwierzbowski commented Nov 14, 2017

Fun coding exercise suggested by Lara Schenck on Twitter: https://twitter.com/laras126/status/929780884835745792.

How my solution works:

  1. Remove all whitespace. Anagrams can be different numbers of words.
  2. Loop!
    1. If either string is empty or they're not equal length, exit the while loop.
    2. Remove all instances of the first letter in lettersA from both strings. Repeat the loop.
  3. Compare strings. If the words are anagrams, both will be '', an empty string.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment