Skip to content

Instantly share code, notes, and snippets.

@deleteman
Created January 13, 2023 18:03
Show Gist options
  • Save deleteman/ad935755e17f20dd331db94a19426b0f to your computer and use it in GitHub Desktop.
Save deleteman/ad935755e17f20dd331db94a19426b0f to your computer and use it in GitHub Desktop.
function findPrefixes(words) {
let sample = words[0]
let currentSet = []
let lastCommonSet = []
let currentPrefix = "";
let lastValidPrefix = "";
for(let i = sample.length; i > 0; i--) {
currentPrefix = sample.slice(0, i)
currentSet = words.filter( w => w.indexOf(currentPrefix) == 0)
if(currentSet.length > 0 && currentSet.length > lastCommonSet.length) {
lastCommonSet = currentSet
lastValidPrefix = currentPrefix
}
}
let toReturn = [lastValidPrefix,
...(lastCommonSet.map(w => w.slice(lastValidPrefix.length))
.filter(w => w.length > 0))]
return {
group: toReturn,
usedWords: lastCommonSet
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment