Skip to content

Instantly share code, notes, and snippets.

@chadoh
Last active September 17, 2019 19:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chadoh/170f439967fde6ab93d1b0d955f5d21b to your computer and use it in GitHub Desktop.
Save chadoh/170f439967fde6ab93d1b0d955f5d21b to your computer and use it in GitHub Desktop.
const ordinalize = (cond1: boolean, cond2: boolean): -1 | 0 | 1 => {
if (cond1 && !cond2) return -1
if (!cond1 && cond2) return 1
return 0
}
const sortResults = (query: string, unsortedList: string[]): string[] => {
const exact = new RegExp(`^${query}$`)
const startsWith = new RegExp(`^${query}`)
const aWordMatchesIn = item => item.split(' ').reduce(
(acc, word) => acc || !!exact.test(word),
false
)
const sortedList = [ ...unsortedList ]
return sortedList.sort((a, b) =>
ordinalize(exact.test(a), exact.test(b)) ||
ordinalize(aWordMatchesIn(a), aWordMatchesIn(b)) ||
ordinalize(startsWith.test(a), startsWith.test(b))
)
}
[{
query: 'omni',
input: ['omni plan', 'pomnit', 'omnigraffle', 'omni'],
}].forEach(({ query, input }) => {
console.log({ input, output: sortResults(query, input) })
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment