Introduction to Fuse.js
Fuse.js is a lightweight fuzzy-search library, built with no dependencies. It is designed for easy integration with web applications, offering a simple but powerful solution for fuzzy search.
We will introduce many of Fuse.js’ useful API methods, complete with code snippets. Additionally, we’ll present a comprehensive example of an app using the introduced APIs.
Setup
<!-- Installing via NPM --> npm install fuse.js
Usage Example
const Fuse = require('fuse.js');
const list = [
"Apple",
"Banana",
"Orange",
"Pineapple",
"Watermelon"
];
const options = {
includeScore: true,
keys: ['name']
};
const fuse = new Fuse(list, options); const result = fuse.search("app"); console.log(result);
Useful API Methods
1. Fuse Constructor
The Fuse constructor initializes a new instance of Fuse.js.
const fuse = new Fuse(list, options);
2. Search Method
Performs a fuzzy search on the given pattern.
const results = fuse.search("your-text");
3. Add Method
Add a new item to the Fuse.js index.
fuse.add("Grapes");
4. Remove Method
Remove an item from the Fuse.js index.
fuse.remove((doc) => doc === "Grapes");
5. SetCollection Method
Reset the Fuse.js collection.
fuse.setCollection(["Mango", "Peach", "Strawberry"]);
6. Index Method
Access the Fuse.js index.
const index = fuse.index();
Comprehensive App Example
Combine the APIs to create a simple search application:
const Fuse = require('fuse.js');
const fruits = [
{ name: "Apple" },
{ name: "Banana" },
{ name: "Orange" },
{ name: "Pineapple" },
{ name: "Watermelon" }
];
const options = {
includeScore: true,
keys: ['name']
};
const fuse = new Fuse(fruits, options);
const searchInput = document.getElementById('search'); const resultContainer = document.getElementById('results');
searchInput.addEventListener('input', () => {
const searchText = searchInput.value;
const results = fuse.search(searchText);
resultContainer.innerHTML = results.map(result => `
<div class="result">
<p>Name: ${result.item.name}</p>
<p>Score: ${result.score}</p>
</div>
`).join('');
});
Conclusion
Fuse.js is an extremely versatile and powerful tool for enabling fuzzy search in your JavaScript applications. With simple integration and various useful methods, it’s a great choice for developers looking to enhance their search capabilities.
Hash: 7106d7d34e9b05e4e290578fd609fafef3cc2a9ea6e43ed3fc512a488eb63008