Skip to content

Instantly share code, notes, and snippets.

@RavenHursT
Created January 22, 2024 15:54
Show Gist options
  • Save RavenHursT/c0f5472c825bf3f0c4b2267c368d4847 to your computer and use it in GitHub Desktop.
Save RavenHursT/c0f5472c825bf3f0c4b2267c368d4847 to your computer and use it in GitHub Desktop.
Compare and find anagrams in an array of strings
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