Customization

Customizing the behavior of the library.

Fuzzy List Options

To customize the search behavior, provide an options object with the following parameters:

index.ts
const fuzzySearch = fuzzy(list, {
  key: "name", // Property to search in the items
  getKey: (item) => [item.name, item.author.fullname], // Search multiple properties
  debug: true, // Enable debugging
  limit: 10, // Max number of results
  maxScore: 2.5, // Max score threshold for results
  mapResult: (item) => item, // Transform the result item
});

key and getKey

If the dataset consists of objects, use key or getKey to specify which properties to search in.

index.ts
type <> = (: string) => {
  : <>[];
  : number;
  : number;
  : string;
  : boolean;
  : <> | null;
  : boolean;
};
 
function <>(: [], ?: <>): <>;
 
const  = [
  { : "volvo", : 2020 },
  { : "seat", : 2019 },
  { : "mercedes", : 2021 },
  { : "audi", : 2022 },
  { : "bmw", : 2023 },
];
 
const  = (, {
  : "name"
});
 
const  = ("volv");
.();

Similarly, getKey allows searching across multiple or nested properties.

index.ts
const  = [
  { : "volvo", : { : "John Doe" } },
  { : "seat", : { : "Jane Doe" } },
  { : "mercedes", : { : "John Smith" } },
];
 
const  = fuzzy(, {
  : () => [.owner.fullname, .name],
});

limit Option

Limits the number of search results returned. Useful for optimizing UI rendering.

index.ts
const  = fuzzy(["volvo", "seat", "mercedes", "audi", "bmw"], {
  : 5,
});

The result set will contain a maximum of 5 items.

maxScore Option

Filters results by score, which represents the distance from an exact match.

index.ts
const  = fuzzy(["volvo", "seat", "mercedes", "audi", "bmw"], {
  : 2, // Exclude results with a score above 2
});

Sorting Behavior

When using both limit and maxScore, results are first filtered by score, then truncated to the limit.

debug Option

Enables logging of search execution details in the console.

index.ts
const  = fuzzy(["volvo", "seat", "mercedes"], {
  : true,
});

mapResult Option

Transforms result items before returning them.

index.ts
const  = fuzzy(["volvo", "seat", "mercedes", "audi", "bmw"], {
  : () => .toUpperCase(),
});
 
const  = ("volvo");
.(.results[0].item); // "VOLVO"

TypeScript Generics

The library uses two generics: one for input type (list items) and another for output type (result items). If mapResult is used, the output type adapts accordingly.

index.ts
function <,  = >(: [], ?: <, >): <>;
Edit on GitHub

Last updated on

On this page