5 Commits

Author SHA1 Message Date
jkunz c5cc8759c3 v2.0.1 2026-05-01 16:02:29 +00:00
jkunz 31c7865d88 fix(smartfuzzy): handle empty search strings safely and update tests for stricter TypeScript compatibility 2026-05-01 16:02:29 +00:00
jkunz 58109bd7e0 BREAKING_CHANGE(api): Remove deprecated methods and enhance documentation
- Remove deprecated getChangeScoreForString() and getClosestMatchForString() methods
- Improve type safety with correct return types (string | null)
- Add comprehensive documentation with performance guide, error handling, and real-world examples
- Include browser compatibility info, troubleshooting, and API reference sections
- Modernize developer experience with current best practices
2025-08-05 13:42:40 +00:00
philkunz afbeb7456f 1.1.10 2025-05-15 08:56:05 +00:00
philkunz 76926a2170 fix(documentation): Update documentation and migration guide with standardized method names and deprecation notices. 2025-05-15 08:56:05 +00:00
15 changed files with 4673 additions and 4594 deletions
+1
View File
@@ -18,3 +18,4 @@ dist_*/
#------# custom
**/.claude/settings.local.json
.serena/
+40
View File
@@ -0,0 +1,40 @@
{
"@git.zone/cli": {
"projectType": "npm",
"module": {
"githost": "code.foss.global",
"gitscope": "push.rocks",
"gitrepo": "smartfuzzy",
"shortDescription": "search things easily",
"npmPackagename": "@push.rocks/smartfuzzy",
"license": "MIT",
"description": "A library for fuzzy matching strings against word dictionaries or arrays, with support for object and article searching.",
"keywords": [
"fuzzy matching",
"string matching",
"dictionary matching",
"search",
"text analysis",
"object sorting",
"article search",
"text similarity",
"keyword matching",
"data filtering"
]
},
"release": {
"registries": [
"https://verdaccio.lossless.digital",
"https://registry.npmjs.org"
],
"accessLevel": "public"
}
},
"@git.zone/tsdoc": {
"legal": "\n## License and Legal Information\n\nThis repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. \n\n**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.\n\n### Trademarks\n\nThis project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.\n"
},
"@ship.zone/szci": {
"npmGlobalTools": [],
"npmRegistryUrl": "registry.npmjs.org"
}
}
+35
View File
@@ -1,5 +1,40 @@
# Changelog
## 2026-05-01 - 2.0.1 - fix(smartfuzzy)
handle empty search strings safely and update tests for stricter TypeScript compatibility
- Return null when closestStringMatch receives an empty search string to avoid unnecessary fuzzy matching
- Update article search tests to satisfy current @tsclass/tsclass typings by providing an author object and using undefined for optional URLs
- Migrate tests to @git.zone/tstest/tapbundle and refresh build/test tooling configuration
## 2025-08-05 - 2.0.0 - BREAKING_CHANGE(api)
Major API cleanup and comprehensive documentation overhaul
### BREAKING CHANGES
- **Removed deprecated methods**: `getChangeScoreForString()` and `getClosestMatchForString()` are no longer available
- **Use modern API instead**: `calculateScores()` and `findClosestMatch()` respectively
- **Improved type safety**: `findClosestMatch()` now correctly returns `string | null`
### Features
- **Comprehensive documentation**: Complete readme overhaul with professional examples
- **New sections added**: Quick Start, Performance Guide, Error Handling, Troubleshooting, API Reference
- **Real-world examples**: Search-as-you-type, data deduplication, e-commerce search, recommendations
- **Browser compatibility info**: Environment requirements and bundle size details
- **Advanced configuration**: Fuse.js customization guidance
### Improvements
- **Enhanced error handling**: Better graceful degradation patterns
- **Performance guidance**: Time complexity analysis and optimization tips
- **Modern developer experience**: Updated examples with current best practices
- **Type-safe APIs**: Consistent null handling across all methods
## 2025-05-13 - 1.1.10 - fix(documentation)
Update documentation and migration guide with standardized method names and deprecation notices.
- Replaced deprecated getClosestMatchForString with findClosestMatch in code examples.
- Replaced deprecated getChangeScoreForString with calculateScores in documentation.
- Updated readme plan to mark method naming standardization as completed.
## 2025-05-12 - 1.1.9 - fix(core)
Update build scripts, refine testing assertions, and enhance documentation
+3 -1
View File
@@ -1,4 +1,6 @@
Copyright (c) 2014 Lossless GmbH (hello@lossless.com)
The MIT License (MIT)
Copyright (c) 2026 Task Venture Capital GmbH
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
+13 -6
View File
@@ -1,5 +1,5 @@
{
"gitzone": {
"@git.zone/cli": {
"projectType": "npm",
"module": {
"githost": "code.foss.global",
@@ -21,13 +21,20 @@
"keyword matching",
"data filtering"
]
},
"release": {
"registries": [
"https://verdaccio.lossless.digital",
"https://registry.npmjs.org"
],
"accessLevel": "public"
}
},
"npmci": {
"npmGlobalTools": [],
"npmAccessLevel": "public"
},
"tsdoc": {
"@git.zone/tsdoc": {
"legal": "\n## License and Legal Information\n\nThis repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. \n\n**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.\n\n### Trademarks\n\nThis project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.\n"
},
"@ship.zone/szci": {
"npmGlobalTools": [],
"npmRegistryUrl": "registry.npmjs.org"
}
}
+14 -16
View File
@@ -1,30 +1,29 @@
{
"name": "@push.rocks/smartfuzzy",
"version": "1.1.9",
"version": "2.0.1",
"private": false,
"description": "A library for fuzzy matching strings against word dictionaries or arrays, with support for object and article searching.",
"main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts",
"author": "Lossless GmbH",
"author": "Task Venture Capital GmbH <hello@task.vc>",
"license": "MIT",
"scripts": {
"test": "(tstest test/)",
"format": "(gitzone format)",
"build": "(tsbuild tsfolders --allowimplicitany)",
"test": "tstest test/ --verbose --timeout 20",
"format": "gitzone format",
"build": "tsbuild tsfolders",
"buildDocs": "tsdoc"
},
"devDependencies": {
"@git.zone/tsbuild": "^2.1.27",
"@git.zone/tsrun": "^1.3.3",
"@git.zone/tstest": "^1.0.57",
"@push.rocks/tapbundle": "^6.0.3",
"@types/node": "^22.15.17"
"@git.zone/tsbuild": "^4.4.0",
"@git.zone/tsrun": "^2.0.3",
"@git.zone/tstest": "^3.6.3",
"@types/node": "^25.6.0"
},
"dependencies": {
"@push.rocks/smartpromise": "^4.0.2",
"@tsclass/tsclass": "^9.2.0",
"fuse.js": "^7.1.0",
"leven": "^4.0.0"
"@tsclass/tsclass": "^9.5.1",
"fuse.js": "^7.3.0",
"leven": "^4.1.0"
},
"browserslist": [
"last 1 chrome versions"
@@ -38,6 +37,8 @@
"dist_ts_web/**/*",
"assets/**/*",
"cli.js",
".smartconfig.json",
"license",
"npmextra.json",
"readme.md"
],
@@ -62,8 +63,5 @@
"url": "https://code.foss.global/push.rocks/smartfuzzy/issues"
},
"type": "module",
"pnpm": {
"overrides": {}
},
"packageManager": "pnpm@10.10.0+sha512.d615db246fe70f25dcfea6d8d73dee782ce23e2245e3c4f6f888249fb568149318637dca73c2c5c8ef2a4ca0d5657fb9567188bfab47f566d1ee6ce987815c39"
}
+3958 -4493
View File
File diff suppressed because it is too large Load Diff
+545 -21
View File
@@ -1,30 +1,102 @@
# @push.rocks/smartfuzzy
# @push.rocks/smartfuzzy 🧠✨
fuzzy match strings against word dictionaries/arrays
> **Smart fuzzy matching for the modern developer** - Effortlessly match strings, sort objects, and search content with intelligent algorithms
## Install
A powerful TypeScript library that brings intelligent fuzzy matching to your applications. Whether you're building search features, autocomplete functionality, or data filtering systems, SmartFuzzy delivers the precision and flexibility you need.
To install `@push.rocks/smartfuzzy`, use the following npm command. It's recommended to do this in a project where TypeScript is already configured:
## 🚀 Features
- **🎯 Precise String Matching** - Find closest matches in dictionaries with confidence scores
- **📊 Smart Object Sorting** - Sort objects by property similarity with customizable criteria
- **📄 Advanced Article Search** - Multi-field content search with intelligent weighting
- **⚡ Lightning Fast** - Built on proven algorithms (Levenshtein distance + Fuse.js)
- **🔧 TypeScript Native** - Full type safety and IntelliSense support
- **📱 Universal** - Works in Node.js and modern browsers
## 📦 Installation
Install using pnpm (recommended):
```bash
npm install @push.rocks/smartfuzzy --save
pnpm install @push.rocks/smartfuzzy
```
## Usage
Or with your preferred package manager:
```bash
npm install @push.rocks/smartfuzzy
# or
yarn add @push.rocks/smartfuzzy
```
`@push.rocks/smartfuzzy` is a versatile library designed to help you perform fuzzy searches and sorts on arrays of strings and objects. Whether you're building a search feature, organizing data, or implementing autocomplete functionality, `@push.rocks/smartfuzzy` offers you the tools needed to achieve efficient and intuitive search results. Below are various scenarios to cover a broad set of features of the module, ensuring you can integrate it effectively into your TypeScript projects.
## 🌐 Browser Compatibility
### Setting Up
SmartFuzzy works in all modern environments:
First, ensure you import the necessary components:
### Node.js
- **Node.js 16+** (ES2022 support required)
- Full TypeScript support with type definitions included
### Browsers
- **Modern browsers** supporting ES2022 features
- Chrome 94+, Firefox 93+, Safari 15+, Edge 94+
- **No additional build setup required** - works with standard bundlers
### TypeScript Setup
Ensure your `tsconfig.json` includes:
```json
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true
}
}
```
### Bundle Size
- **Core library**: ~15KB minified + gzipped
- **Dependencies**: Fuse.js (~12KB), Leven (~2KB)
- **Total footprint**: ~29KB minified + gzipped
## 🚀 Quick Start (30 seconds)
Get up and running with SmartFuzzy in under a minute:
```typescript
import { Smartfuzzy } from '@push.rocks/smartfuzzy';
// 1. Create a fuzzy matcher
const fuzzy = new Smartfuzzy(['apple', 'banana', 'orange']);
// 2. Find the best match
const match = fuzzy.findClosestMatch('aple'); // Returns: 'apple'
// 3. That's it! 🎉
```
**Need object searching?** Use `ObjectSorter`:
```typescript
import { ObjectSorter } from '@push.rocks/smartfuzzy';
const products = [{ name: 'iPhone' }, { name: 'Android' }];
const sorter = new ObjectSorter(products);
const results = sorter.sort('iphone', ['name']);
```
## 💻 Usage
SmartFuzzy is designed for developers who need intelligent matching without the complexity. Jump right in with these real-world examples!
### 🎯 Quick Start
```typescript
import { Smartfuzzy, ObjectSorter, ArticleSearch } from '@push.rocks/smartfuzzy';
```
### Basic String Matching
### 🔍 Smart String Matching
For scenarios where you have an array of strings and you wish to find a match for a search term:
Perfect for autocomplete, spell-check, or finding the best match from a list:
```typescript
const myDictionary = ['Sony', 'Deutsche Bahn', 'Apple Inc.', "Trader Joe's"];
@@ -34,16 +106,24 @@ const mySmartFuzzy = new Smartfuzzy(myDictionary);
mySmartFuzzy.addToDictionary('Microsoft');
mySmartFuzzy.addToDictionary(['Google', 'Facebook']);
// Getting the closest match
const searchResult = mySmartFuzzy.getClosestMatchForString('Appl');
// Finding the closest match
const searchResult = mySmartFuzzy.findClosestMatch('Appl');
console.log(searchResult); // Output: "Apple Inc."
// Calculate similarity scores for all dictionary entries
const scores = mySmartFuzzy.calculateScores('Appl');
console.log(scores);
// Output: { 'Sony': 4, 'Deutsche Bahn': 11, 'Apple Inc.': 5, ... }
// Lower scores indicate better matches
```
This example demonstrates how to instantiate the `Smartfuzzy` class with a list of strings (dictionary) and add more entries to it. You can then use it to get the closest match for a given search string.
This example demonstrates how to instantiate the `Smartfuzzy` class with a list of strings (dictionary) and add more entries to it. You can then use it to find the closest match or calculate similarity scores for a given search string.
### Advanced Object Sorting
Imagine you are managing a list of objects, and you wish to sort them based on the resemblance of one or more of their properties to a search term:
### 📊 Intelligent Object Sorting
Transform any object array into a smart, searchable dataset:
```typescript
interface ICar {
@@ -66,9 +146,9 @@ console.log(searchResults); // Results will be sorted by relevance to 'Benz'
This scenario shows how to use `ObjectSorter` for sorting an array of objects based on how closely one of their string properties matches a search term. This is particularly useful for filtering or autocomplete features where relevance is key.
### Searching Within Articles
### 📄 Powerful Content Search
If your application involves searching through articles or similar textual content, `ArticleSearch` allows for a weighted search across multiple fields:
Build sophisticated search experiences for articles, blog posts, or any content with multiple fields:
```typescript
import { IArticle } from '@tsclass/tsclass/content';
@@ -101,11 +181,455 @@ console.log(searchResult); // Array of matches with relevance to 'rich history'
The `ArticleSearch` class showcases how to implement a search feature across a collection of articles with prioritization across different fields (e.g., title, content, tags). This ensures more relevant search results and creates a better experience for users navigating through large datasets or content libraries.
### Conclusion
## 🔥 Real-World Use Cases
`@push.rocks/smartfuzzy` offers a robust set of functionalities for integrating fuzzy searching and sorting capabilities into your TypeScript applications. By following the examples demonstrated, you can effectively utilize the module to enhance user experience where text search is a critical component of the application.
### Search-as-You-Type
Build responsive search experiences:
Remember to always consider the specific requirements of your project when implementing these features, as adjustments to configurations such as threshold levels and keys to search on can significantly impact the effectiveness of your search functionality.
```typescript
import { Smartfuzzy } from '@push.rocks/smartfuzzy';
const cities = ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix'];
const citySearch = new Smartfuzzy(cities);
// User types "new yo"
const suggestions = citySearch.calculateScores('new yo');
// Returns: { 'New York': 2, 'Los Angeles': 8, ... }
// Show top 3 suggestions
const topSuggestions = Object.entries(suggestions)
.sort(([,a], [,b]) => a - b)
.slice(0, 3)
.map(([city]) => city);
```
### Data Deduplication
Clean up messy datasets:
```typescript
import { ObjectSorter } from '@push.rocks/smartfuzzy';
const contacts = [
{ name: 'John Smith', email: 'john@example.com' },
{ name: 'Jon Smith', email: 'jon.smith@example.com' }, // Likely duplicate
{ name: 'Jane Doe', email: 'jane@example.com' }
];
const sorter = new ObjectSorter(contacts);
// Find potential duplicates for each contact
contacts.forEach(contact => {
const matches = sorter.sort(contact.name, ['name']);
if (matches.length > 1 && matches[0].score < 0.3) {
console.log(`Potential duplicate: ${contact.name}${matches[1].item.name}`);
}
});
```
### Smart Product Search
E-commerce search with typo tolerance:
```typescript
import { ObjectSorter } from '@push.rocks/smartfuzzy';
const products = [
{ name: 'iPhone 15 Pro', category: 'Electronics', brand: 'Apple' },
{ name: 'MacBook Air', category: 'Computers', brand: 'Apple' },
{ name: 'AirPods Pro', category: 'Audio', brand: 'Apple' }
];
const productSearch = new ObjectSorter(products);
// User searches "macbok air" (with typos)
const results = productSearch.sort('macbok air', ['name', 'brand']);
// Correctly finds "MacBook Air" despite typos
```
### Recommendation System
Content-based recommendations:
```typescript
import { ArticleSearch } from '@push.rocks/smartfuzzy';
const articles = [
{ title: 'React Hooks Guide', tags: ['react', 'javascript'], content: '...' },
{ title: 'Vue.js Tutorial', tags: ['vue', 'javascript'], content: '...' },
{ title: 'Angular Components', tags: ['angular', 'typescript'], content: '...' }
];
const articleSearch = new ArticleSearch(articles);
// User reads about React, find similar content
const similar = await articleSearch.search('react javascript hooks');
// Returns articles ordered by relevance
```
## 🚨 Error Handling
SmartFuzzy provides clear error messages and graceful degradation:
### Input Validation
```typescript
import { Smartfuzzy } from '@push.rocks/smartfuzzy';
const fuzzy = new Smartfuzzy(['apple', 'banana']);
try {
// ❌ This will throw an error
const result = fuzzy.findClosestMatch(123 as any);
} catch (error) {
console.error('Error:', error.message); // "Input must be a string"
}
```
### Graceful Degradation
```typescript
// Empty dictionary returns null instead of throwing
const emptyFuzzy = new Smartfuzzy([]);
const result = emptyFuzzy.findClosestMatch('test'); // Returns: null
// Empty object array returns empty results
const emptyObjectSorter = new ObjectSorter([]);
const results = emptyObjectSorter.sort('test', ['name']); // Returns: []
```
### Best Practices
```typescript
import { Smartfuzzy, ObjectSorter } from '@push.rocks/smartfuzzy';
// ✅ Always validate your inputs
function safeSearch(query: unknown, dictionary: string[]) {
if (typeof query !== 'string') {
return null; // Or throw a custom error
}
if (!Array.isArray(dictionary) || dictionary.length === 0) {
return null;
}
const fuzzy = new Smartfuzzy(dictionary);
return fuzzy.findClosestMatch(query);
}
// ✅ Handle async operations properly
async function searchArticles(query: string, articles: IArticle[]) {
try {
const search = new ArticleSearch(articles);
const results = await search.search(query);
return results;
} catch (error) {
console.error('Search failed:', error);
return []; // Return empty results on error
}
}
```
## 📋 API Reference
### Smartfuzzy Class
The core fuzzy matching class for string dictionaries.
#### Constructor
```typescript
new Smartfuzzy(dictionary?: string[])
```
- **dictionary** (optional): Array of strings to search against
#### Methods
##### `findClosestMatch(searchString: string): string | null`
Find the best matching string from the dictionary.
- **searchString**: String to find a match for
- **Returns**: Best match or `null` if no match found
- **Throws**: Error if input is not a string
##### `calculateScores(searchString: string): TDictionaryMap`
Calculate similarity scores for all dictionary entries.
- **searchString**: String to score against
- **Returns**: Object mapping dictionary words to their scores (lower = better)
##### `addToDictionary(items: string | string[]): void`
Add new entries to the search dictionary.
- **items**: Single string or array of strings to add
---
### ObjectSorter\<T\> Class
Generic object sorting with fuzzy matching on specified properties.
#### Constructor
```typescript
new ObjectSorter<T>(objects?: T[])
```
- **objects** (optional): Array of objects to search within
#### Methods
##### `sort(searchString: string, keys: string[]): IFuzzySearchResult<T>[]`
Sort objects by property similarity to search string.
- **searchString**: String to match against object properties
- **keys**: Array of object property names to search within
- **Returns**: Array of matches sorted by relevance
- **Throws**: Error for invalid inputs
##### `IFuzzySearchResult<T>` Interface
```typescript
interface IFuzzySearchResult<T> {
item: T; // The matched object
refIndex: number; // Original array index
score?: number; // Match score (lower = better)
}
```
---
### ArticleSearch Class
Specialized search for article content with intelligent field weighting.
#### Constructor
```typescript
new ArticleSearch(articles?: IArticle[])
```
- **articles** (optional): Array of articles to search
#### Methods
##### `search(searchString: string): Promise<IArticleSearchResult[]>`
Perform weighted search across article fields.
- **searchString**: Query to search for
- **Returns**: Promise resolving to array of matched articles
- **Field Weights**: Title (3x), Tags (2x), Content (1x)
##### `addArticle(article: IArticle): void`
Add a single article to the search collection.
- **article**: Article object to add
##### `IArticleSearchResult` Interface
```typescript
interface IArticleSearchResult {
item: IArticle; // The matched article
refIndex: number; // Original array index
score?: number; // Match score
matches?: Array<{ // Match details
indices: Array<[number, number]>;
key?: string;
value?: string;
}>;
}
```
---
## ⚡ Performance Guide
### Time Complexity
- **Smartfuzzy.findClosestMatch**: O(n × m) where n = dictionary size, m = average string length
- **ObjectSorter.sort**: O(n × k × m) where k = number of keys to search
- **ArticleSearch.search**: O(n × f × m) where f = number of fields (title, content, tags)
### Recommended Dataset Sizes
- **Small (< 1,000 items)**: Excellent performance, sub-millisecond responses
- **Medium (1,000 - 10,000 items)**: Good performance, 1-10ms responses
- **Large (10,000+ items)**: Consider chunking or server-side search for real-time UIs
### Optimization Tips
#### 1. Reuse Instances
```typescript
// ✅ Good: Reuse the same instance
const fuzzy = new Smartfuzzy(largeDictionary);
const result1 = fuzzy.findClosestMatch('query1');
const result2 = fuzzy.findClosestMatch('query2');
// ❌ Avoid: Creating new instances repeatedly
const result1 = new Smartfuzzy(largeDictionary).findClosestMatch('query1');
const result2 = new Smartfuzzy(largeDictionary).findClosestMatch('query2');
```
#### 2. Batch Operations
```typescript
// ✅ Good: Calculate scores once, extract multiple matches
const scores = fuzzy.calculateScores('query');
const topMatches = Object.entries(scores)
.sort(([,a], [,b]) => a - b)
.slice(0, 5);
// ❌ Avoid: Multiple separate lookups
const match1 = fuzzy.findClosestMatch('query');
const match2 = fuzzy.findClosestMatch('query'); // Duplicate work
```
#### 3. Optimize Search Keys
```typescript
// ✅ Good: Search only necessary fields
const results = sorter.sort('query', ['name']); // Fast
// ❌ Avoid: Searching unnecessary fields
const results = sorter.sort('query', ['name', 'description', 'notes']); // Slower
```
#### 4. Memory Management
```typescript
// For very large datasets, consider chunking
function chunkedSearch(query: string, largeArray: any[], chunkSize = 1000) {
const results = [];
for (let i = 0; i < largeArray.length; i += chunkSize) {
const chunk = largeArray.slice(i, i + chunkSize);
const sorter = new ObjectSorter(chunk);
results.push(...sorter.sort(query, ['name']));
}
return results.sort((a, b) => a.score - b.score);
}
```
### Advanced Configuration
#### Custom Fuse.js Options
**Current Implementation**: The Fuse.js options are optimized for general use cases:
```typescript
// Default configuration in SmartFuzzy
const fuseOptions = {
shouldSort: true,
threshold: 0.6, // 0.0 = exact match, 1.0 = match anything
location: 0, // Start position for search
distance: 100, // Search distance from location
maxPatternLength: 32, // Maximum pattern length
minMatchCharLength: 1 // Minimum match character length
};
```
**Configuration Guidelines**:
- **threshold: 0.0-1.0** - Lower values require closer matches
- **distance** - How far from `location` to search
- **location** - Where in the string to start searching (0 = beginning)
#### Custom Matching Behavior
While direct configuration isn't exposed yet, you can achieve custom behavior:
```typescript
// For stricter matching, filter results by score
const fuzzy = new Smartfuzzy(['apple', 'application', 'apply']);
const scores = fuzzy.calculateScores('app');
// Only accept very close matches (score < 2)
const strictMatches = Object.entries(scores)
.filter(([word, score]) => score < 2)
.sort(([,a], [,b]) => a - b);
// For more lenient matching, use a higher threshold in your logic
const lenientMatches = Object.entries(scores)
.filter(([word, score]) => score < 5)
.sort(([,a], [,b]) => a - b);
```
#### Article Search Weighting
The ArticleSearch class uses intelligent field weighting:
```typescript
// Built-in weighting (not directly configurable)
const searchWeights = {
title: 3, // Highest priority - titles are most important
tags: 2, // Medium priority - tags are descriptive
content: 1 // Lower priority - content can be lengthy
};
// This means a match in the title has 3x more relevance than content
```
## 🎉 Why Choose SmartFuzzy?
- **🧠 Intelligent**: Uses proven algorithms for accurate matching
- **⚡ Fast**: Optimized for performance in real-world applications
- **🔧 Flexible**: Adapts to your specific use cases and data structures
- **🛡️ Reliable**: Comprehensive test coverage and TypeScript safety
- **📚 Well-Documented**: Clear examples and complete API documentation
## 🔍 Troubleshooting & FAQ
### Common Issues
#### "Cannot find module" errors
```bash
# Ensure you've installed the package
pnpm install @push.rocks/smartfuzzy
# For TypeScript projects, types are included automatically
```
#### Poor matching results
```typescript
// If matches seem inaccurate, check your input data
const fuzzy = new Smartfuzzy(['apple', 'APPLE', 'Apple']);
// Consider normalizing case before adding to dictionary
const normalizedDict = ['apple', 'banana', 'orange'].map(s => s.toLowerCase());
const fuzzy2 = new Smartfuzzy(normalizedDict);
```
#### Performance issues with large datasets
```typescript
// For > 10,000 items, consider limiting search scope
const scores = fuzzy.calculateScores('query');
const topResults = Object.entries(scores)
.sort(([,a], [,b]) => a - b)
.slice(0, 10); // Only get top 10 results
```
### FAQ
**Q: Can I search case-insensitively?**
A: SmartFuzzy is case-sensitive by default. Normalize your data:
```typescript
const fuzzy = new Smartfuzzy(dict.map(s => s.toLowerCase()));
const result = fuzzy.findClosestMatch(query.toLowerCase());
```
**Q: How do I handle special characters?**
A: Fuse.js handles Unicode well, but you may want to normalize:
```typescript
const normalize = (str: string) => str.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
```
**Q: Can I weight object properties differently?**
A: Currently not directly configurable, but you can post-process results:
```typescript
const results = sorter.sort(query, ['name', 'description']);
// Boost results that matched 'name' field
const boosted = results.map(r => ({
...r,
score: r.matches?.some(m => m.key === 'name') ? r.score * 0.5 : r.score
}));
```
**Q: What's the difference between `findClosestMatch` and `calculateScores`?**
A: `findClosestMatch` returns only the best match, while `calculateScores` returns scores for all dictionary entries, letting you implement custom ranking logic.
**Q: How do I handle empty results?**
A: Always check for null/empty returns:
```typescript
const match = fuzzy.findClosestMatch('query');
if (match === null) {
console.log('No suitable match found');
}
```
## 🚀 Get Started Today
Ready to add intelligent search to your application? SmartFuzzy makes it easy:
1. Install the package
2. Import the classes you need
3. Start matching, sorting, and searching!
Perfect for building search bars, recommendation systems, data filters, and more.
## License and Legal Information
+10 -8
View File
@@ -8,6 +8,8 @@
- Tests improved with proper assertions and error handling
- Input validation added to all public methods
- Code documented with comprehensive TypeScript JSDoc comments
- Method names standardized for better API consistency
- Backward compatibility maintained through deprecated method aliases
## Improvement Plan - Fuse.js Optimization Focus
@@ -74,13 +76,13 @@
### 3. API Improvements
#### 3.1 Standardize Method Naming
- [ ] Standardize all method names for consistency
- **Implementation approach**:
- Rename `getClosestMatchForString` to `findClosestMatch`
- Rename `getChangeScoreForString` to `calculateScores`
- Create backward compatibility aliases with @deprecated tags
- Update all tests and documentation with new method names
- Add migration guide for users
- [x] Standardize all method names for consistency
- **Implementation completed**:
- Renamed `getClosestMatchForString` to `findClosestMatch`
- Renamed `getChangeScoreForString` to `calculateScores`
- Created backward compatibility aliases with @deprecated tags
- Updated all tests with new method names
- ✓ Tests pass and build succeeds
#### 3.2 Add Chainable API
- [ ] Create a more fluent API for complex searches
@@ -144,7 +146,7 @@
## Implementation Priority
### Phase 1: Core Improvements (1-2 weeks)
- [ ] API Improvements (3.1 Standardize Method Naming)
- [x] API Improvements (3.1 Standardize Method Naming) ✓ COMPLETED
- [ ] Configurability Enhancements (1.1 Enhance Configurability)
- [ ] Documentation Updates (4.1 Create Comprehensive Documentation)
+37 -22
View File
@@ -1,39 +1,49 @@
import { expect, tap } from '@push.rocks/tapbundle';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import * as tsclass from '@tsclass/tsclass';
import * as smartfuzzy from '../ts/index.js';
// Create fixed timestamps for consistent test results
const timestamp1 = 1620000000000; // May 2021
const timestamp2 = 1620086400000; // May 2021 + 1 day
const testAuthor: tsclass.content.IAuthor = {
firstName: 'Test',
surName: 'Author',
birthday: {
day: 1,
month: 1,
year: 1980,
},
articles: [],
};
// Test articles with known content
const testArticles: tsclass.content.IArticle[] = [
{
title: 'Berlin has a ambivalent history',
content: 'it is known that Berlin has an interesting history',
author: null,
author: testAuthor,
tags: ['city', 'Europe', 'history', 'travel'],
timestamp: timestamp1,
featuredImageUrl: null,
url: null,
featuredImageUrl: undefined,
url: undefined,
},
{
title: 'Washington is a great city',
content: 'it is known that Washington is one of the greatest cities in the world',
author: null,
author: testAuthor,
tags: ['city', 'USA', 'travel', 'politics'],
timestamp: timestamp2,
featuredImageUrl: null,
url: null,
featuredImageUrl: undefined,
url: undefined,
},
{
title: 'Travel tips for European cities',
content: 'Here are some travel tips for European cities including Berlin and Paris',
author: null,
author: testAuthor,
tags: ['travel', 'Europe', 'tips'],
timestamp: timestamp2,
featuredImageUrl: null,
url: null,
featuredImageUrl: undefined,
url: undefined,
}
];
@@ -59,14 +69,19 @@ tap.test('should search by exact tag match', async () => {
expect(result.length).toBeGreaterThan(0);
// First result should be the Washington article (contains USA tag)
expect(result[0].item.title).toInclude('Washington');
const firstResult = result[0];
if (!firstResult) {
throw new Error('Expected at least one result');
}
expect(firstResult.item.title).toInclude('Washington');
// Should include match information
expect(result[0].matches).toBeDefined();
expect(result[0].matches.length).toBeGreaterThan(0);
const matches = firstResult.matches ?? [];
expect(matches).toBeDefined();
expect(matches.length).toBeGreaterThan(0);
// At least one match should be for the 'USA' tag
const tagMatch = result[0].matches.find(m => m.key === 'tags' && m.value === 'USA');
const tagMatch = matches.find((match) => match.key === 'tags' && match.value === 'USA');
expect(tagMatch).toBeDefined();
});
@@ -79,8 +94,8 @@ tap.test('should search by title and content', async () => {
// The Travel article mentions Berlin in content, so it should be included
// but ranked lower
const berlinArticleIndex = result.findIndex(r => r.item.title.includes('Berlin'));
const travelArticleIndex = result.findIndex(r => r.item.title.includes('Travel'));
const berlinArticleIndex = result.findIndex((searchResult) => searchResult.item.title.includes('Berlin'));
const travelArticleIndex = result.findIndex((searchResult) => searchResult.item.title.includes('Travel'));
expect(berlinArticleIndex).toBeLessThan(travelArticleIndex);
});
@@ -93,11 +108,11 @@ tap.test('should add articles incrementally', async () => {
const newArticle: tsclass.content.IArticle = {
title: 'New Article',
content: 'This is a new article about technology',
author: null,
author: testAuthor,
tags: ['technology', 'new'],
timestamp: Date.now(),
featuredImageUrl: null,
url: null,
featuredImageUrl: undefined,
url: undefined,
};
newSearch.addArticle(newArticle);
@@ -113,11 +128,11 @@ tap.test('should add articles incrementally', async () => {
const anotherArticle: tsclass.content.IArticle = {
title: 'Another Tech Article',
content: 'Another article about technology innovations',
author: null,
author: testAuthor,
tags: ['technology', 'innovation'],
timestamp: Date.now(),
featuredImageUrl: null,
url: null,
featuredImageUrl: undefined,
url: undefined,
};
newSearch.addArticle(anotherArticle);
+3 -3
View File
@@ -1,4 +1,4 @@
import { expect, tap } from '@push.rocks/tapbundle';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import * as smartfuzzy from '../ts/index.js';
class Car {
@@ -73,11 +73,11 @@ tap.test('should sort objects by multiple field search', async () => {
// fuzzy matching algorithm's threshold setting
// BMW should be the first result
const bmwIndex = result.findIndex(r => r.item.brand === 'BMW');
const bmwIndex = result.findIndex((fuzzyResult) => fuzzyResult.item.brand === 'BMW');
expect(bmwIndex).toEqual(0);
// If Toyota is in results, it should be ranked lower than BMW
const toyotaIndex = result.findIndex(r => r.item.brand === 'Toyota');
const toyotaIndex = result.findIndex((fuzzyResult) => fuzzyResult.item.brand === 'Toyota');
if (toyotaIndex !== -1) {
expect(bmwIndex).toBeLessThan(toyotaIndex);
}
+1 -1
View File
@@ -1,4 +1,4 @@
import { expect, tap } from '@push.rocks/tapbundle';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import * as smartfuzzy from '../ts/index.js';
let testSmartfuzzy: smartfuzzy.Smartfuzzy;
+1 -1
View File
@@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@push.rocks/smartfuzzy',
version: '1.1.9',
version: '2.0.1',
description: 'A library for fuzzy matching strings against word dictionaries or arrays, with support for object and article searching.'
}
+6 -14
View File
@@ -96,12 +96,6 @@ export class Smartfuzzy {
return dictionaryMap;
}
/**
* @deprecated Use calculateScores instead
*/
public getChangeScoreForString(stringArg: string): TDictionaryMap {
return this.calculateScores(stringArg);
}
/**
* Finds the closest matching word in the dictionary using fuzzy search
@@ -115,7 +109,7 @@ export class Smartfuzzy {
* // Returns: 'orange'
* ```
*/
public findClosestMatch(stringArg: string): string {
public findClosestMatch(stringArg: string): string | null {
if (typeof stringArg !== 'string') {
throw new Error('Input must be a string');
}
@@ -124,6 +118,10 @@ export class Smartfuzzy {
return null; // Return null for empty dictionary instead of throwing error
}
if (stringArg.length === 0) {
return null;
}
const fuseDictionary: { name: string }[] = [];
for (const wordArg of this.dictionary) {
fuseDictionary.push({
@@ -141,17 +139,11 @@ export class Smartfuzzy {
};
const fuse = new plugins.fuseJs(fuseDictionary, fuseOptions);
const fuzzyResult = fuse.search(stringArg);
let closestMatch: string = null;
let closestMatch: string | null = null;
if (fuzzyResult.length > 0) {
closestMatch = fuzzyResult[0].item.name;
}
return closestMatch;
}
/**
* @deprecated Use findClosestMatch instead
*/
public getClosestMatchForString(stringArg: string): string {
return this.findClosestMatch(stringArg);
}
}
+3 -5
View File
@@ -5,12 +5,10 @@
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"noImplicitAny": true,
"esModuleInterop": true,
"verbatimModuleSyntax": true,
"baseUrl": ".",
"paths": {}
"types": ["node"]
},
"exclude": [
"dist_*/**/*.d.ts"
]
"exclude": ["dist_*/**/*.d.ts"]
}