Last active
September 17, 2019 19:36
-
-
Save chadoh/170f439967fde6ab93d1b0d955f5d21b to your computer and use it in GitHub Desktop.
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 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