Introduction to Fuse.js
Fuse.js is a powerful and lightweight fuzzy-search library, that allows you to perform efficient and flexible search queries on data. It is simple to use and can be seamlessly integrated into any JavaScript application.
Getting Started with Fuse.js
First, you need to install Fuse.js to your project:
npm install fuse.js
Basic Usage
Here is a basic example on how to initialize and use Fuse.js:
const Fuse = require('fuse.js');
const list = [
{title: "Old Man's War", author: "John Scalzi"},
{title: "The Lock Artist", author: "Steve Hamilton"},
{title: "HTML5", author: "Remy Sharp"},
{title: "Right Ho Jeeves", author: "P.D. Wodehouse"},
];
const options = {keys: ['title', 'author']};
const fuse = new Fuse(list, options);
const result = fuse.search('Steve');
console.log(result);
Advanced Options
Fuse.js comes with a range of powerful options to customize its search behavior:
isCaseSensitive
: Perform a case-sensitive search.includeScore
: Includes the search score in the result.shouldSort
: Sort the result list, by score.threshold
: At what point does the match algorithm give up. A threshold of 0.0 requires a perfect match (of both letters and location), and a threshold of 1.0 would match anything.
Example with advanced options:
const options = {
keys: ['title'],
includeScore: true,
threshold: 0.2,
location: 0,
distance: 100,
maxPatternLength: 32,
minMatchCharLength: 2,
shouldSort: true,
findAllMatches: false,
};
Diving Deeper with Fuse.js API
Fuse.js also provides several APIs for more control:
fuse.setCollection(list)
: Dynamically update the collection you want to search against.fuse.add(item)
: Add a new item to the existing collection.fuse.remove(predicate)
: Remove items from the collection that match the predicate.fuse.getIndex()
: Retrieve the current data index.
Real-world Application Example
Here is a simple web application using Fuse.js:
Fuse.js Example App
Book Search
In this example, we have an input field to search through a list of books dynamically.
Hash: 7106d7d34e9b05e4e290578fd609fafef3cc2a9ea6e43ed3fc512a488eb63008