fuzzySearch.tsx 766 B

12345678910111213141516171819202122232425262728293031
  1. import type Fuse from 'fuse.js';
  2. // See http://fusejs.io/ for more information
  3. const DEFAULT_FUSE_OPTIONS: Fuse.IFuseOptions<any> = {
  4. includeScore: true,
  5. includeMatches: true,
  6. threshold: 0.4,
  7. location: 0,
  8. distance: 75,
  9. minMatchCharLength: 2,
  10. };
  11. export async function createFuzzySearch<
  12. T = string,
  13. Options extends Fuse.IFuseOptions<T> = Fuse.IFuseOptions<T>
  14. >(objects: T[], options: Options): Promise<Fuse<T>> {
  15. if (!options.keys) {
  16. throw new Error('You need to define `options.keys`');
  17. }
  18. const fuseImported = await import('fuse.js');
  19. const fuse = {Fuse: fuseImported.default};
  20. return new fuse.Fuse(objects, {
  21. ...DEFAULT_FUSE_OPTIONS,
  22. ...options,
  23. });
  24. }
  25. // re-export fuse type to make it easier to use
  26. export type {Fuse};