Skip to content

Instantly share code, notes, and snippets.

@gko
Created December 26, 2020 11:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gko/5ec9be1fc0f9c5b7593309f4a4d91120 to your computer and use it in GitHub Desktop.
Save gko/5ec9be1fc0f9c5b7593309f4a4d91120 to your computer and use it in GitHub Desktop.
// https://twitter.com/fermatslibrary/status/875340896379817984/photo/1
const memoizedWords: {
[Key: string]: number;
} = {};
const ALPHABET_MAPPED_TO_PRIME_NUMBERS: {
[Key: string]: number;
} = {
a: 2,
b: 3,
c: 5,
d: 7,
e: 11,
f: 13,
g: 17,
h: 19,
i: 23,
j: 29,
k: 31,
l: 37,
m: 41,
n: 43,
o: 47,
p: 53,
q: 59,
r: 61,
s: 67,
t: 71,
u: 73,
v: 79,
w: 83,
x: 89,
y: 97,
z: 101,
};
const wordProduct = (word: string) => {
const lowerCaseWord: string = word.toLowerCase();
return (
memoizedWords[lowerCaseWord] ||
((memoizedWords[lowerCaseWord] = lowerCaseWord
.split("")
.reduce(
(acc, letter) => acc * ALPHABET_MAPPED_TO_PRIME_NUMBERS[letter],
1
)),
memoizedWords[lowerCaseWord])
);
};
const isAnagram = (wordA: string, wordB: string) => {
if (wordB === wordA) return false;
return wordProduct(wordA) === wordProduct(wordB);
};
export { isAnagram };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment