Created
January 22, 2024 15:54
-
-
Save RavenHursT/c0f5472c825bf3f0c4b2267c368d4847 to your computer and use it in GitHub Desktop.
Compare and find anagrams in an array of strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const wordsAreAnagrams = (a: string, b: string) => | |
a.split("").sort().join("") === b.split("").sort().join("") | |
const findAnagram = (word: string, compareList: string[]) => { | |
let result = null | |
compareList.every((w: string) => { | |
if (wordsAreAnagrams(word, w)) { | |
result = w | |
return false | |
} | |
return true | |
}) | |
return result | |
} | |
const getAnagramCounts = (list: string[]) => | |
list.reduce( | |
( | |
agg: { | |
[key: string]: number | |
}, | |
incoming: string | |
) => { | |
const currentBaseWords = Object.keys(agg) | |
const word = incoming.toLowerCase() | |
const anagramCountExists = findAnagram(word, currentBaseWords) | |
return anagramCountExists | |
? { | |
...agg, | |
[anagramCountExists]: agg[anagramCountExists] + 1, | |
} | |
: { ...agg, [word]: 0 } | |
}, | |
{} | |
) | |
const maxAnagrams = (list: string[]) => { | |
const anagramCount = getAnagramCounts(list) | |
const highestAnagramWord = Object.entries(anagramCount).sort((a, b) => | |
a[1] < b[1] ? 1 : -1 | |
) | |
return highestAnagramWord[0] && highestAnagramWord[0][0] | |
? highestAnagramWord[0][0] | |
: "" | |
} | |
console.assert(maxAnagrams(["his", "tokyo", "sih", "Kyoto", "ish"]) === "his") | |
console.assert( | |
maxAnagrams([ | |
"abets", | |
"taser", | |
"baste", | |
"aster", | |
"stare brake", | |
"tears break", | |
"baker rates", | |
]) === "stare brake" | |
) | |
console.info("All assertions passed") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment