Last active
January 3, 2021 20:52
-
-
Save createdbymahmood/b1790c394e5d3b19deb6853422a0d1c9 to your computer and use it in GitHub Desktop.
Fuzzy Search in JS/TS World!
This file contains hidden or 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
/* picked from cypress-realworld-app */ | |
import Fuse from "fuse.js"; | |
import { flow, map, curry } from "lodash/fp"; | |
type IItems = { | |
title: string; | |
body: string; | |
}; | |
export const performSearch = (items: object[], options: {}, query: string) => | |
flow( | |
cleanSearchQuery, | |
setupSearch(items, options), | |
map((result: Fuse.FuseResult<IItems>) => result.item) | |
)(query); | |
export const cleanSearchQuery = (query: string) => | |
query.replace(/[^a-zA-Z0-9]/g, ""); | |
export const setupSearch = curry( | |
(items: object[], options: {}, query: string) => { | |
const fuse = new Fuse(items, options); | |
return fuse.search(query); | |
} | |
); | |
export const searchUsers = (query: string) => { | |
const items = [ | |
{ | |
title: "Lorem ipsum dolor sit amet, consectetur adipiscing elit,", | |
body: "sed do eiusmod tempor", | |
}, | |
{ | |
title: "incididunt ut labore et dolore", | |
body: "magna aliqua. Ut", | |
}, | |
{ | |
title: "enim ad minim veniam, ", | |
body: "nostrud exercitation", | |
}, | |
{ | |
title: "ullamco laboris nisi ut aliquip", | |
body: "ex ea commodo consequat", | |
}, | |
{ | |
title: "QueryString uis aute irure dolor in reprehenderit in", | |
body: | |
"voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur si", | |
}, | |
]; | |
return performSearch( | |
items, | |
{ | |
keys: ["title", "body"], | |
}, | |
query | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment