### Fuzzyset Installation with npm
Source: https://github.com/glench/fuzzyset.js/blob/master/README.MD
Provides the command-line instruction to install the fuzzyset.js library using npm, the Node Package Manager. This is the standard method for incorporating the library into a Node.js project.
```bash
npm install fuzzyset
```
--------------------------------
### Browser Usage with CDN
Source: https://context7.com/glench/fuzzyset.js/llms.txt
Demonstrates how to load and use FuzzySet directly in an HTML file via a CDN, eliminating the need for a build system. This example shows how to initialize FuzzySet with a list of countries and implement a live search functionality for an input field, displaying matching results in a designated div. It highlights the global availability of the FuzzySet object.
```html
FuzzySet Example
```
--------------------------------
### Fuzzyset Methods: get, add, length, isEmpty, values
Source: https://github.com/glench/fuzzyset.js/blob/master/README.MD
Provides examples of using the primary methods of the Fuzzyset class. The `get` method retrieves approximate matches, `add` inserts new values, `length` returns the count of items, `isEmpty` checks if the set is empty, and `values` returns all stored strings.
```javascript
// Add a value
mySet.add('cherry');
// Get matches with a minimum score
const matches = mySet.get('appel', null, 0.7);
// Get the number of items
const count = mySet.length();
// Check if empty
const empty = mySet.isEmpty();
// Get all values
const allValues = mySet.values();
```
--------------------------------
### Fuzzy String Matching with FuzzySet.get()
Source: https://context7.com/glench/fuzzyset.js/llms.txt
Illustrates how to use the `get` method to find approximate matches for a given string. It covers basic usage, setting a minimum score threshold, providing a default fallback value, and handling typos.
```javascript
import FuzzySet from 'fuzzyset'
const names = FuzzySet([
'Michael Jackson',
'Michael Jordan',
'Michelle Obama',
'Mike Tyson'
])
// Basic fuzzy matching
const result1 = names.get('micael jackson')
// [[0.8461538461538461, 'Michael Jackson']]
const result2 = names.get('michelle')
// [[1, 'Michelle Obama']]
// With custom minimum score (default: 0.33)
const result3 = names.get('john', null, 0.5)
// null (no matches above 0.5)
const result4 = names.get('mich', null, 0.3)
// [[0.6666666666666666, 'Michelle Obama'], [0.6, 'Michael Jordan'], [0.6, 'Michael Jackson']]
// With default fallback value
const result5 = names.get('xyz', 'No match found')
// 'No match found'
// Handle typos in search
const products = FuzzySet(['iPhone 14', 'iPad Pro', 'MacBook Air'])
console.log(products.get('iphone 14')) // [[1, 'iPhone 14']]
console.log(products.get('ipone')) // [[0.6923076923076923, 'iPhone 14']]
console.log(products.get('macbok air')) // [[0.8695652173913043, 'MacBook Air']]
```
--------------------------------
### get(value, [default], [minScore])
Source: https://context7.com/glench/fuzzyset.js/llms.txt
Search for approximate matches with configurable minimum score threshold.
```APIDOC
## get(value, [default], [minScore])
### Description
Search for approximate matches with configurable minimum score threshold.
### Method
`get(value: string, defaultValue?: any, minScore?: number): Array<[number, string]> | any | null`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **value** (string) - Required - The string value to search for.
- **defaultValue** (any) - Optional - A fallback value to return if no matches are found.
- **minScore** (number) - Optional - The minimum similarity score (0 to 1) for a match to be considered valid. Defaults to 0.33.
### Request Example
```javascript
import FuzzySet from 'fuzzyset'
const names = FuzzySet([
'Michael Jackson',
'Michael Jordan',
'Michelle Obama',
'Mike Tyson'
])
// Basic fuzzy matching
const result1 = names.get('micael jackson')
// [[0.8461538461538461, 'Michael Jackson']]
const result2 = names.get('michelle')
// [[1, 'Michelle Obama']]
// With custom minimum score (default: 0.33)
const result3 = names.get('john', null, 0.5)
// null (no matches above 0.5)
const result4 = names.get('mich', null, 0.3)
// [[0.6666666666666666, 'Michelle Obama'], [0.6, 'Michael Jordan'], [0.6, 'Michael Jackson']]
// With default fallback value
const result5 = names.get('xyz', 'No match found')
// 'No match found'
// Handle typos in search
const products = FuzzySet(['iPhone 14', 'iPad Pro', 'MacBook Air'])
console.log(products.get('iphone 14')) // [[1, 'iPhone 14']]
console.log(products.get('ipone')) // [[0.6923076923076923, 'iPhone 14']]
console.log(products.get('macbok air')) // [[0.8695652173913043, 'MacBook Air']]
```
### Response
#### Success Response (200)
- **Return Value** (Array<[number, string]> | any | null) - Returns an array of matches, where each match is a tuple `[score, value]`, or the `defaultValue` if no matches are found, or `null` if no `defaultValue` is provided and no matches are found.
```
--------------------------------
### Node.js CommonJS Usage
Source: https://context7.com/glench/fuzzyset.js/llms.txt
Shows how to use FuzzySet within a Node.js environment using the CommonJS `require` syntax. This example demonstrates loading a dictionary of words from a file, creating a FuzzySet instance, and then implementing a command-line interface for fuzzy searching. It utilizes the `readline` and `fs` modules to interact with the user and the file system, providing suggestions for misspelled words.
```javascript
const FuzzySet = require('fuzzyset')
// Command-line fuzzy finder
const readline = require('readline')
const fs = require('fs')
// Load dictionary from file
const dictionary = fs.readFileSync('/usr/share/dict/words', 'utf8')
.split('\n')
.filter(word => word.length > 3)
const fuzzyDict = FuzzySet(dictionary)
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
rl.question('Enter a word (possibly misspelled): ', (input) => {
const matches = fuzzyDict.get(input, null, 0.5)
if (matches) {
console.log('\nDid you mean:')
matches.slice(0, 5).forEach(([score, word]) => {
console.log(` ${word} (${(score * 100).toFixed(1)}% match)`)
})
} else {
console.log('No close matches found')
}
rl.close()
})
```
--------------------------------
### TypeScript Usage with FuzzySet
Source: https://context7.com/glench/fuzzyset.js/llms.txt
Illustrates the seamless integration of FuzzySet.js with TypeScript projects. This example defines a `ProductSearcher` class that utilizes FuzzySet for efficient searching of product names. It demonstrates type safety by using TypeScript interfaces for products and generics for the FuzzySet instance, providing type hints for better code maintainability and fewer runtime errors.
```typescript
import FuzzySet from 'fuzzyset'
interface Product {
id: string
name: string
category: string
}
class ProductSearcher {
private fuzzySet: ReturnType
private products: Map
constructor(products: Product[]) {
this.products = new Map()
const names: string[] = []
products.forEach(product => {
this.products.set(product.name, product)
names.push(product.name)
})
this.fuzzySet = FuzzySet(names)
}
search(query: string, minScore: number = 0.4): Product[] {
const matches = this.fuzzySet.get(query, null, minScore)
if (!matches) return []
return matches
.map(([score, name]) => this.products.get(name))
.filter((p): p is Product => p !== undefined)
}
}
// Usage
const products: Product[] = [
{ id: '1', name: 'iPhone 14 Pro', category: 'phone' },
{ id: '2', name: 'Samsung Galaxy S23', category: 'phone' },
{ id: '3', name: 'MacBook Pro 16', category: 'laptop' }
]
const searcher = new ProductSearcher(products)
const results = searcher.search('iphone 14')
console.log(results)
// [{ id: '1', name: 'iPhone 14 Pro', category: 'phone' }]
```
--------------------------------
### Retrieve All Values from FuzzySet
Source: https://context7.com/glench/fuzzyset.js/llms.txt
Shows how to use the `values()` method to get an array containing all the original strings stored in the FuzzySet. This is useful for iteration or verification purposes.
```javascript
import FuzzySet from 'fuzzyset'
const animals = FuzzySet(['cat', 'dog', 'elephant', 'zebra'])
console.log(animals.values())
// ['cat', 'dog', 'elephant', 'zebra']
animals.add('tiger')
console.log(animals.values())
// ['cat', 'dog', 'elephant', 'zebra', 'tiger']
// Useful for iteration or verification
const current = animals.values()
current.forEach(animal => console.log(`Animal: ${animal}`))
```
--------------------------------
### Get Count of Items in FuzzySet
Source: https://context7.com/glench/fuzzyset.js/llms.txt
Demonstrates the `length()` method, which returns the total number of unique strings currently stored in the FuzzySet. Adding a duplicate does not increase the count.
```javascript
import FuzzySet from 'fuzzyset'
const colors = FuzzySet(['red', 'blue', 'green'])
console.log(colors.length()) // 3
colors.add('yellow')
console.log(colors.length()) // 4
colors.add('red') // Duplicate, not added
console.log(colors.length()) // 4
```
--------------------------------
### Initialize FuzzySet Instances
Source: https://context7.com/glench/fuzzyset.js/llms.txt
Demonstrates various ways to create a FuzzySet instance, including empty sets, pre-loaded sets, and sets with custom matching parameters like Levenshtein distance and gram size ranges.
```javascript
import FuzzySet from 'fuzzyset'
// Create empty set
const fs = FuzzySet()
// Initialize with data
const cities = FuzzySet(['San Francisco', 'Los Angeles', 'New York', 'Chicago'])
// Configure matching parameters
const custom = FuzzySet(
['apple', 'banana', 'orange'],
true, // useLevenshtein (default: true)
2, // gramSizeLower (default: 2)
3 // gramSizeUpper (default: 3)
)
// Without Levenshtein for faster matching
const fast = FuzzySet(['item1', 'item2'], false)
```
--------------------------------
### Building Fuzzyset.js from Source
Source: https://github.com/glench/fuzzyset.js/blob/master/README.MD
Explains the development workflow for Fuzzyset.js, including how to build the distributable files after making changes to the source code. The `npm run build` command generates the various file formats in the `dist/` directory, while `npm run dev` enables auto-building during development.
```bash
# Build the project
npm run build
# Run in development mode with auto-building
npm run dev
```
--------------------------------
### Initializing Fuzzyset with Options
Source: https://github.com/glench/fuzzyset.js/blob/master/README.MD
Demonstrates how to instantiate the FuzzySet object with optional constructor arguments to customize its behavior. Options include pre-populating with an array of strings and configuring the matching algorithm parameters like Levenshtein distance and gram size.
```javascript
// Example: Initialize with an array and custom gram sizes
const mySet = FuzzySet(['apple', 'banana', 'apricot'], true, 2, 4);
// Example: Default initialization
const defaultSet = FuzzySet();
```
--------------------------------
### FuzzySet Initialization
Source: https://context7.com/glench/fuzzyset.js/llms.txt
Initialize a new FuzzySet with optional configuration for matching behavior and gram size ranges.
```APIDOC
## FuzzySet Initialization
### Description
Initialize a new FuzzySet with optional configuration for matching behavior and gram size ranges.
### Method
`FuzzySet(values?, useLevenshtein?, gramSizeLower?, gramSizeUpper?)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
import FuzzySet from 'fuzzyset'
// Create empty set
const fs = FuzzySet()
// Initialize with data
const cities = FuzzySet(['San Francisco', 'Los Angeles', 'New York', 'Chicago'])
// Configure matching parameters
const custom = FuzzySet(
['apple', 'banana', 'orange'],
true, // useLevenshtein (default: true)
2, // gramSizeLower (default: 2)
3 // gramSizeUpper (default: 3)
)
// Without Levenshtein for faster matching
const fast = FuzzySet(['item1', 'item2'], false)
```
### Response
#### Success Response (200)
Returns an instance of FuzzySet.
#### Response Example
```json
{
"instance": "FuzzySet object"
}
```
```
--------------------------------
### Including Fuzzyset in Web Projects
Source: https://github.com/glench/fuzzyset.js/blob/master/README.MD
Illustrates how to include the Fuzzyset.js library in an HTML file for direct use in web browsers. This method utilizes a script tag to load the library from a local or CDN path.
```html
```
--------------------------------
### Autocomplete Implementation with Fuzzy Matching
Source: https://context7.com/glench/fuzzyset.js/llms.txt
Presents an implementation of a real-time autocomplete system using fuzzy matching capabilities of FuzzySet.js. The `Autocomplete` class allows for dynamic addition of items and provides a `suggest` method that returns ranked suggestions based on a query. It includes configurable options for minimum match score and the number of results, along with confidence levels for each suggestion.
```javascript
import FuzzySet from 'fuzzyset'
class Autocomplete {
constructor(items, options = {}) {
this.minScore = options.minScore || 0.4
this.maxResults = options.maxResults || 5
this.fuzzySet = FuzzySet(items, true, 2, 3)
}
suggest(input) {
if (!input || input.length < 2) return []
const matches = this.fuzzySet.get(input, null, this.minScore)
if (!matches) return []
return matches
.slice(0, this.maxResults)
.map(([score, value]) => ({
value,
score,
confidence: score >= 0.8 ? 'high' : score >= 0.5 ? 'medium' : 'low'
}))
}
addItem(item) {
return this.fuzzySet.add(item)
}
getSize() {
return this.fuzzySet.length()
}
}
// Example: Email domain autocomplete
const emailDomains = [
'gmail.com',
'yahoo.com',
'hotmail.com',
'outlook.com',
'protonmail.com',
'icloud.com'
]
const autocomplete = new Autocomplete(emailDomains, {
minScore: 0.3,
maxResults: 3
})
console.log(autocomplete.suggest('gmial'))
// [
// { value: 'gmail.com', score: 0.8, confidence: 'high' },
// { value: 'hotmail.com', score: 0.48, confidence: 'low' }
// ]
console.log(autocomplete.suggest('outlok'))
// [
// { value: 'outlook.com', score: 0.7272727272727273, confidence: 'medium' }
// ]
```
--------------------------------
### Importing Fuzzyset in Node.js
Source: https://github.com/glench/fuzzyset.js/blob/master/README.MD
Shows two common ways to import the FuzzySet class in a Node.js environment. The first uses ES Module syntax (`import`), while the second uses CommonJS syntax (`require`).
```javascript
import FuzzySet from 'fuzzyset'
// or, depending on your JavaScript environment...
const FuzzySet = require('fuzzyset')
```
--------------------------------
### Basic Fuzzyset Usage and Retrieval
Source: https://github.com/glench/fuzzyset.js/blob/master/README.MD
Demonstrates the core functionality of Fuzzyset.js by adding a string to the set and then retrieving approximate matches. The output is an array of [score, matched_value] pairs, where the score indicates the match quality.
```javascript
a = FuzzySet();
a.add("michael axiak");
a.get("micael asiak");
// will be [[0.8461538461538461, 'michael axiak']];
```
--------------------------------
### values()
Source: https://context7.com/glench/fuzzyset.js/llms.txt
Retrieve an array of all original strings stored in the FuzzySet.
```APIDOC
## values()
### Description
Retrieve an array of all original strings stored in the FuzzySet.
### Method
`values(): string[]`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
import FuzzySet from 'fuzzyset'
const animals = FuzzySet(['cat', 'dog', 'elephant', 'zebra'])
console.log(animals.values())
// ['cat', 'dog', 'elephant', 'zebra']
animals.add('tiger')
console.log(animals.values())
// ['cat', 'dog', 'elephant', 'zebra', 'tiger']
// Useful for iteration or verification
const current = animals.values()
current.forEach(animal => console.log(`Animal: ${animal}`))
```
### Response
#### Success Response (200)
- **Return Value** (Array) - An array containing all unique strings currently stored in the FuzzySet.
```
--------------------------------
### Check if FuzzySet is Empty
Source: https://context7.com/glench/fuzzyset.js/llms.txt
Explains how to use the `isEmpty()` method to check if the FuzzySet contains any strings. It returns `true` for an empty set and `false` otherwise.
```javascript
import FuzzySet from 'fuzzyset'
const empty = FuzzySet()
console.log(empty.isEmpty()) // true
empty.add('something')
console.log(empty.isEmpty()) // false
const preloaded = FuzzySet(['item1', 'item2'])
console.log(preloaded.isEmpty()) // false
```
--------------------------------
### isEmpty()
Source: https://context7.com/glench/fuzzyset.js/llms.txt
Determine whether the FuzzySet contains any strings.
```APIDOC
## isEmpty()
### Description
Determine whether the FuzzySet contains any strings.
### Method
`isEmpty(): boolean`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
import FuzzySet from 'fuzzyset'
const empty = FuzzySet()
console.log(empty.isEmpty()) // true
empty.add('something')
console.log(empty.isEmpty()) // false
const preloaded = FuzzySet(['item1', 'item2'])
console.log(preloaded.isEmpty()) // false
```
### Response
#### Success Response (200)
- **Return Value** (boolean) - Returns `true` if the FuzzySet is empty, `false` otherwise.
```
--------------------------------
### Add Strings to FuzzySet
Source: https://context7.com/glench/fuzzyset.js/llms.txt
Shows how to add individual strings or build a FuzzySet incrementally from an array. It also notes that adding a duplicate string returns `false`.
```javascript
import FuzzySet from 'fuzzyset'
const names = FuzzySet()
// Add single items
names.add('Michael Jackson')
names.add('Michael Jordan')
names.add('Michelle Obama')
// Returns false if already exists
const result1 = names.add('Michael Jackson') // false
const result2 = names.add('Mike Tyson') // undefined (success)
// Build dictionary incrementally
const products = FuzzySet()
const inventory = ['iPhone 14', 'iPad Pro', 'MacBook Air', 'AirPods Pro']
inventory.forEach(item => products.add(item))
```
--------------------------------
### add(value)
Source: https://context7.com/glench/fuzzyset.js/llms.txt
Add new strings to the FuzzySet for future matching operations.
```APIDOC
## add(value)
### Description
Add new strings to the FuzzySet for future matching operations.
### Method
`add(value: string): boolean | undefined`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **value** (string) - Required - The string value to add to the set.
### Request Example
```javascript
import FuzzySet from 'fuzzyset'
const names = FuzzySet()
// Add single items
names.add('Michael Jackson')
names.add('Michael Jordan')
names.add('Michelle Obama')
// Returns false if already exists
const result1 = names.add('Michael Jackson') // false
const result2 = names.add('Mike Tyson') // undefined (success)
// Build dictionary incrementally
const products = FuzzySet()
const inventory = ['iPhone 14', 'iPad Pro', 'MacBook Air', 'AirPods Pro']
inventory.forEach(item => products.add(item))
```
### Response
#### Success Response (200)
- **Return Value** (boolean | undefined) - Returns `false` if the value already exists in the set, otherwise returns `undefined` upon successful addition.
```
--------------------------------
### length()
Source: https://context7.com/glench/fuzzyset.js/llms.txt
Return the total number of unique strings in the FuzzySet.
```APIDOC
## length()
### Description
Return the total number of unique strings in the FuzzySet.
### Method
`length(): number`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
import FuzzySet from 'fuzzyset'
const colors = FuzzySet(['red', 'blue', 'green'])
console.log(colors.length()) // 3
colors.add('yellow')
console.log(colors.length()) // 4
colors.add('red') // Duplicate, not added
console.log(colors.length()) // 4
```
### Response
#### Success Response (200)
- **Return Value** (number) - The total count of unique strings in the FuzzySet.
```
--------------------------------
### JavaScript: Deduplicate Items with Fuzzy Matching
Source: https://context7.com/glench/fuzzyset.js/llms.txt
This JavaScript function utilizes FuzzySet.js to identify and group duplicate items within a list, even if they have minor spelling variations. It requires the 'fuzzyset' library. The function takes an array of items and a similarity threshold as input, returning unique items and a list of detected duplicates with their similarity scores.
```javascript
import FuzzySet from 'fuzzyset'
function findDuplicates(items, threshold = 0.85) {
const fuzzySet = FuzzySet()
const duplicates = []
const unique = []
items.forEach(item => {
const match = fuzzySet.get(item, null, threshold)
if (match) {
// Found potential duplicate
duplicates.push({
original: match[0][1],
duplicate: item,
similarity: match[0][0]
})
} else {
// Unique item
fuzzySet.add(item)
unique.push(item)
}
})
return { unique, duplicates }
}
// Example: Clean customer database
const customers = [
'John Smith',
'Jon Smith',
'John Smyth',
'Jane Doe',
'Jane doe',
'Michael Johnson',
'Bob Williams'
]
const result = findDuplicates(customers, 0.85)
console.log('Unique customers:', result.unique)
// ['John Smith', 'Jane Doe', 'Michael Johnson', 'Bob Williams']
console.log('Duplicates found:', result.duplicates)
// [
// { original: 'John Smith', duplicate: 'Jon Smith', similarity: 0.9 },
// { original: 'John Smith', duplicate: 'John Smyth', similarity: 0.9 },
// { original: 'Jane Doe', duplicate: 'Jane doe', similarity: 1 }
// ]
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.