13 Commits

24 changed files with 10738 additions and 26061 deletions

View File

@ -0,0 +1,66 @@
name: Default (not tags)
on:
push:
tags-ignore:
- '**'
env:
IMAGE: code.foss.global/host.today/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Install pnpm and npmci
run: |
pnpm install -g pnpm
pnpm install -g @ship.zone/npmci
- name: Run npm prepare
run: npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build

View File

@ -0,0 +1,124 @@
name: Default (tags)
on:
push:
tags:
- '*'
env:
IMAGE: code.foss.global/host.today/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @ship.zone/npmci
npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @ship.zone/npmci
npmci npm prepare
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build
release:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @ship.zone/npmci
npmci npm prepare
- name: Release
run: |
npmci node install stable
npmci npm publish
metadata:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
continue-on-error: true
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @ship.zone/npmci
npmci npm prepare
- name: Code quality
run: |
npmci command npm install -g typescript
npmci npm install
- name: Trigger
run: npmci trigger
- name: Build docs and upload artifacts
run: |
npmci node install stable
npmci npm install
pnpm install -g @git.zone/tsdoc
npmci command tsdoc
continue-on-error: true

3
.gitignore vendored
View File

@ -3,7 +3,6 @@
# artifacts
coverage/
public/
pages/
# installs
node_modules/
@ -17,4 +16,4 @@ node_modules/
dist/
dist_*/
# custom
#------# custom

View File

@ -1,138 +0,0 @@
# gitzone ci_default
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
cache:
paths:
- .npmci_cache/
key: '$CI_BUILD_STAGE'
stages:
- security
- test
- release
- metadata
# ====================
# security stage
# ====================
mirror:
stage: security
script:
- npmci git mirror
only:
- tags
tags:
- lossless
- docker
- notpriv
auditProductionDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci npm prepare
- npmci command npm install --production --ignore-scripts
- npmci command npm config set registry https://registry.npmjs.org
- npmci command npm audit --audit-level=high --only=prod --production
tags:
- docker
allow_failure: true
auditDevDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci npm prepare
- npmci command npm install --ignore-scripts
- npmci command npm config set registry https://registry.npmjs.org
- npmci command npm audit --audit-level=high --only=dev
tags:
- docker
allow_failure: true
# ====================
# test stage
# ====================
testStable:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
testBuild:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci command npm run build
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
release:
stage: release
script:
- npmci node install stable
- npmci npm publish
only:
- tags
tags:
- lossless
- docker
- notpriv
# ====================
# metadata stage
# ====================
codequality:
stage: metadata
allow_failure: true
only:
- tags
script:
- npmci command npm install -g tslint typescript
- npmci npm prepare
- npmci npm install
- npmci command "tslint -c tslint.json ./ts/**/*.ts"
tags:
- lossless
- docker
- priv
trigger:
stage: metadata
script:
- npmci trigger
only:
- tags
tags:
- lossless
- docker
- notpriv
pages:
stage: metadata
script:
- npmci node install lts
- npmci command npm install -g @gitzone/tsdoc
- npmci npm prepare
- npmci npm install
- npmci command tsdoc
tags:
- lossless
- docker
- notpriv
only:
- tags
artifacts:
expire_in: 1 week
paths:
- public
allow_failure: true

60
changelog.md Normal file
View File

@ -0,0 +1,60 @@
# Changelog
## 2025-05-12 - 1.1.8 - fix(tests)
Standardize test syntax and update testing dependencies
- Added @git.zone/tsrun dependency to package.json for improved test runner support
- Refactored test export in test/test.articlesearch.ts to use default export instead of tap.start()
- Updated readme.plan.md to describe testing improvements and syntax standardization
## 2025-05-12 - 1.1.7 - fix(build)
Fix import paths, update CI workflows and upgrade dependencies for ESM compliance
- Updated import statements to include .js extensions for NodeNext compatibility
- Upgraded dependencies: @push.rocks/smartpromise (^4.0.2), @tsclass/tsclass (^9.2.0), fuse.js (^7.1.0), leven (^4.0.0), and @push.rocks/tapbundle (^6.0.3)
- Added new workflow files for CI (default_tags.yaml and default_nottags.yaml)
- Revised test files and documentation to reflect file path and dependency changes
- Minor adjustments in package.json (scripts and metadata) and tsconfig for enhanced module resolution
## 2024-05-29 - 1.1.6 - maintenance
This release brings a series of configuration and documentation updates as well as an organizational change.
- Updated project description.
- Revised tsconfig settings.
- Updated npmextra.json with new githost details (merged from several commits).
- Switched to a new organization scheme.
(Note: A prior commit “1.1.6” from 2021 was a version bump and is omitted here.)
## 2021-10-04 - 1.1.5 - core
Core components were fixed in this update.
- fix(core): update
## 2021-10-03 - 1.1.4
This version was released as a version bump without additional significant changes.
## 2021-10-03 - 1.1.3 - core
Minor fixes were applied to core functionality.
- fix(core): update
## 2021-10-03 - 1.1.2 - core
Additional improvements and fixes to the core components.
- fix(core): update
## 2021-10-03 - 1.1.1 - core
A further core update fixing underlying issues.
- fix(core): update
## 2018-08-19 - 1.1.0 - Smartfuzzy
A fix was introduced for Smartfuzzys matching functionality.
- fix(Smartfuzzy.getClosestMatchForString() now returns the cloesest string directly): update
## 2018-08-19 - 1.0.3 - ObjectSorter
A new feature has been added to sort objects by likability.
- feat(ObjectSorter): now sorts objects by likability
## 2018-08-19 - 1.0.2 - package
An adjustment was made to the package name in the npm configuration.
- fix(package): npm name
## 2018-08-19 - 1.0.1 - package
Initial package fixes were applied.
- fix(package): initial

19
license Normal file
View File

@ -0,0 +1,19 @@
Copyright (c) 2014 Lossless GmbH (hello@lossless.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -2,16 +2,32 @@
"gitzone": {
"projectType": "npm",
"module": {
"githost": "gitlab.com",
"gitscope": "pushrocks",
"githost": "code.foss.global",
"gitscope": "push.rocks",
"gitrepo": "smartfuzzy",
"shortDescription": "search things easily",
"npmPackagename": "@pushrocks/smartfuzzy",
"license": "MIT"
"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"
]
}
},
"npmci": {
"npmGlobalTools": [],
"npmAccessLevel": "public"
},
"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"
}
}

25847
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,8 +1,8 @@
{
"name": "@pushrocks/smartfuzzy",
"version": "1.1.5",
"name": "@push.rocks/smartfuzzy",
"version": "1.1.8",
"private": false,
"description": "fuzzy match strings against word dictionaries/arrays",
"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",
@ -10,19 +10,21 @@
"scripts": {
"test": "(tstest test/)",
"format": "(gitzone format)",
"build": "(tsbuild)"
"build": "(tsbuild)",
"buildDocs": "tsdoc"
},
"devDependencies": {
"@gitzone/tsbuild": "^2.1.27",
"@gitzone/tstest": "^1.0.57",
"@pushrocks/tapbundle": "^3.2.14",
"@types/node": "^16.10.2"
"@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"
},
"dependencies": {
"@pushrocks/smartpromise": "^3.1.6",
"@tsclass/tsclass": "^3.0.33",
"fuse.js": "^6.4.6",
"leven": "^3.1.0"
"@push.rocks/smartpromise": "^4.0.2",
"@tsclass/tsclass": "^9.2.0",
"fuse.js": "^7.1.0",
"leven": "^4.0.0"
},
"browserslist": [
"last 1 chrome versions"
@ -38,5 +40,30 @@
"cli.js",
"npmextra.json",
"readme.md"
]
],
"keywords": [
"fuzzy matching",
"string matching",
"dictionary matching",
"search",
"text analysis",
"object sorting",
"article search",
"text similarity",
"keyword matching",
"data filtering"
],
"homepage": "https://code.foss.global/push.rocks/smartfuzzy#readme",
"repository": {
"type": "git",
"url": "https://code.foss.global/push.rocks/smartfuzzy.git"
},
"bugs": {
"url": "https://code.foss.global/push.rocks/smartfuzzy/issues"
},
"type": "module",
"pnpm": {
"overrides": {}
},
"packageManager": "pnpm@10.10.0+sha512.d615db246fe70f25dcfea6d8d73dee782ce23e2245e3c4f6f888249fb568149318637dca73c2c5c8ef2a4ca0d5657fb9567188bfab47f566d1ee6ce987815c39"
}

10043
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

1
readme.hints.md Normal file
View File

@ -0,0 +1 @@

127
readme.md Normal file
View File

@ -0,0 +1,127 @@
# @push.rocks/smartfuzzy
fuzzy match strings against word dictionaries/arrays
## Install
To install `@push.rocks/smartfuzzy`, use the following npm command. It's recommended to do this in a project where TypeScript is already configured:
```bash
npm install @push.rocks/smartfuzzy --save
```
## Usage
`@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.
### Setting Up
First, ensure you import the necessary components:
```typescript
import { Smartfuzzy, ObjectSorter, ArticleSearch } from '@push.rocks/smartfuzzy';
```
### Basic String Matching
For scenarios where you have an array of strings and you wish to find a match for a search term:
```typescript
const myDictionary = ['Sony', 'Deutsche Bahn', 'Apple Inc.', "Trader Joe's"];
const mySmartFuzzy = new Smartfuzzy(myDictionary);
// Adding additional dictionary entries
mySmartFuzzy.addToDictionary('Microsoft');
mySmartFuzzy.addToDictionary(['Google', 'Facebook']);
// Getting the closest match
const searchResult = mySmartFuzzy.getClosestMatchForString('Appl');
console.log(searchResult); // Output: "Apple Inc."
```
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.
### 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:
```typescript
interface ICar {
brand: string;
model: string;
}
const carList: ICar[] = [
{ brand: 'BMW', model: 'M3' },
{ brand: 'Mercedes Benz', model: 'E-Class' },
{ brand: 'Volvo', model: 'XC90' },
];
const carSorter = new ObjectSorter<ICar>(carList);
// Search and sort based on brand similarity
const searchResults = carSorter.sort('Benz', ['brand']);
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
If your application involves searching through articles or similar textual content, `ArticleSearch` allows for a weighted search across multiple fields:
```typescript
import { IArticle } from '@tsclass/tsclass/content';
const articles: IArticle[] = [
{
title: 'History of Berlin',
content: 'Berlin has a rich history...',
tags: ['history', 'Berlin'],
timestamp: Date.now(),
featuredImageUrl: null,
url: null,
},
{
title: 'Tourism in Berlin',
content: 'Discover the vibrant city of Berlin...',
tags: ['travel', 'Berlin'],
timestamp: Date.now(),
featuredImageUrl: null,
url: null,
},
];
const articleSearch = new ArticleSearch(articles);
// Perform a search across titles, content, and tags
const searchResult = await articleSearch.search('rich history');
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
`@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.
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.
## License and Legal Information
This 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.
**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.
### Trademarks
This 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.
### Company Information
Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
By 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.

72
readme.plan.md Normal file
View File

@ -0,0 +1,72 @@
# SmartFuzzy Improvement Plan
## Current Status
- ESM imports/exports fixed with .js extensions
- Basic fuzzy matching functionality works
- Testing infrastructure fixed with @git.zone/tsrun dependency
- Test syntax needs standardization (converting from chai-style to SmartExpect syntax)
- Using older versions of dependencies
## Improvement Plan
### 1. Testing Improvements
#### 1.1 Update Test Syntax and Standards
- [ ] Convert all tests from chai-style syntax (`expect().to.be`) to SmartExpect syntax (`expect().toBeInstanceOf()`)
- [ ] Implement consistent test structure across all test files
- [ ] Add proper setup and teardown patterns where needed
- [ ] Replace console.log statements with proper assertions to validate results
- [ ] Add descriptive error messages to assertions to improve test debugging
#### 1.2 Expand Test Coverage
- [ ] Add tests for empty dictionaries and edge cases
- [ ] Test with extremely large dictionaries to verify performance
- [ ] Add tests for unicode/special character handling
- [ ] Test with very similar strings to validate fuzzy matching accuracy
- [ ] Add tests for error conditions and input validation
- [ ] Implement tests for all public APIs and features
### 2. Code Quality Improvements
- [ ] Add proper TypeScript documentation comments to all public methods
- [ ] Implement consistent error handling
- [ ] Add input validation for all public methods
- [ ] Standardize method naming conventions (e.g., get* vs find*)
### 3. Feature Enhancements
- [ ] Add configurable threshold options for matching
- [ ] Implement stemming/lemmatization support for better text matching
- [ ] Add language-specific matching options
- [ ] Support for weighted matching across multiple fields
- [ ] Add batch processing capabilities for large datasets
### 4. Performance Optimizations
- [ ] Implement caching for repeated searches
- [ ] Optimize indexing for large dictionaries
- [ ] Add benchmarking tests to measure performance improvements
### 5. Dependencies and Build System
- [ ] Update to latest versions of dependencies
- [ ] Ensure proper tree-shaking for browser bundle
- [ ] Add browser-specific build configuration
- [ ] Implement proper ES module / CommonJS dual package setup
### 6. Documentation
- [ ] Create comprehensive API documentation
- [ ] Add usage examples for common scenarios
- [ ] Create benchmarks comparing to other fuzzy matching libraries
- [ ] Document performance characteristics and optimization strategies
### 7. Developer Experience
- [ ] Add VS Code debugging configuration
- [ ] Implement changelog generation
- [ ] Set up automated release process
- [ ] Add contribution guidelines
## Priority Order
1. Fix testing infrastructure (critical)
2. Code quality improvements (high)
3. Documentation (high)
4. Feature enhancements (medium)
5. Performance optimizations (medium)
6. Dependencies and build system (medium)
7. Developer experience (low)

View File

@ -1,6 +1,6 @@
import { expect, tap } from '@pushrocks/tapbundle';
import { expect, tap } from '@push.rocks/tapbundle';
import * as tsclass from '@tsclass/tsclass';
import * as smartfuzzy from '../ts/index';
import * as smartfuzzy from '../ts/index.js';
tap.test('should sort objects', async () => {
const articleArray: tsclass.content.IArticle[] = [
@ -31,4 +31,4 @@ tap.test('should sort objects', async () => {
console.log(result[0].matches);
});
tap.start();
export default tap.start();

View File

@ -1,21 +1,81 @@
import { expect, tap } from '@pushrocks/tapbundle';
import * as smartfuzzy from '../ts/index';
import { expect, tap } from '@push.rocks/tapbundle';
import * as smartfuzzy from '../ts/index.js';
tap.test('should sort objects', async () => {
class Car {
constructor(public brand: string) {}
constructor(public brand: string, public model?: string, public year?: number) {}
}
let testObjectSorter: smartfuzzy.ObjectSorter<Car>;
const testCars = [
new Car('BMW', 'X5', 2022),
new Car('Mercedes Benz', 'S-Class', 2021),
new Car('Volvo', 'XC90', 2023),
new Car('Volkswagen', 'Golf', 2020),
new Car('Audi', 'A4', 2022),
];
testObjectSorter = new smartfuzzy.ObjectSorter([
new Car('BMW'),
new Car('Mercedes Benz'),
new Car('Volvo'),
]);
let objectSorter: smartfuzzy.ObjectSorter<Car>;
const result = testObjectSorter.sort('Volvo', ['brand']);
console.log(result);
tap.test('should create an instance of ObjectSorter', async () => {
objectSorter = new smartfuzzy.ObjectSorter<Car>(testCars);
expect(objectSorter).toBeInstanceOf(smartfuzzy.ObjectSorter);
expect(objectSorter.objectDictionary).toEqual(testCars);
// Test empty constructor
const emptyObjectSorter = new smartfuzzy.ObjectSorter<Car>();
expect(emptyObjectSorter.objectDictionary).toEqual([]);
});
tap.start();
tap.test('should sort objects by exact brand match', async () => {
const result = objectSorter.sort('Volvo', ['brand']);
// Should return an array of results
expect(result).toBeArray();
expect(result.length).toBeGreaterThan(0);
// First result should be the Volvo
expect(result[0].item.brand).toEqual('Volvo');
// Should have expected result structure
expect(result[0]).toHaveProperty('item');
expect(result[0]).toHaveProperty('refIndex');
expect(result[0].refIndex).toBeTypeofNumber();
// Reference index should match the original array position
expect(result[0].refIndex).toEqual(2); // Volvo is at index 2
});
tap.test('should sort objects by fuzzy brand match', async () => {
// "Wolvo" should fuzzy match to "Volvo"
const result = objectSorter.sort('Wolvo', ['brand']);
expect(result.length).toBeGreaterThan(0);
expect(result[0].item.brand).toEqual('Volvo');
});
tap.test('should sort objects by multiple field search', async () => {
// Add a car with similar model name but different brand
objectSorter = new smartfuzzy.ObjectSorter<Car>([
...testCars,
new Car('Toyota', 'X5 Replica', 2020),
]);
// Search across both brand and model
const result = objectSorter.sort('BMW X5', ['brand', 'model']);
expect(result.length).toBeGreaterThan(0);
// BMW X5 should be first result
expect(result[0].item.brand).toEqual('BMW');
expect(result[0].item.model).toEqual('X5');
// Toyota X5 Replica should also be in results but lower ranked
const toyotaResult = result.find(r => r.item.brand === 'Toyota');
expect(toyotaResult).toBeDefined();
// Toyota should be ranked lower than BMW
const bmwIndex = result.findIndex(r => r.item.brand === 'BMW');
const toyotaIndex = result.findIndex(r => r.item.brand === 'Toyota');
expect(bmwIndex).toBeLessThan(toyotaIndex);
});
export default tap.start();

View File

@ -1,26 +1,67 @@
import { expect, tap } from '@pushrocks/tapbundle';
import * as smartfuzzy from '../ts/index';
import { expect, tap } from '@push.rocks/tapbundle';
import * as smartfuzzy from '../ts/index.js';
let testSmartfuzzy: smartfuzzy.Smartfuzzy;
tap.test('should create an instance of Smartfuzzy', async () => {
testSmartfuzzy = new smartfuzzy.Smartfuzzy([
const testDictionary = [
'Sony',
'Deutsche Bahn',
'Apple Inc.',
"Trader Joe's",
]);
expect(testSmartfuzzy).to.be.instanceof(smartfuzzy.Smartfuzzy);
];
tap.test('should create an instance of Smartfuzzy', async () => {
testSmartfuzzy = new smartfuzzy.Smartfuzzy(testDictionary);
expect(testSmartfuzzy).toBeInstanceOf(smartfuzzy.Smartfuzzy);
expect(testSmartfuzzy.dictionary).toEqual(testDictionary);
});
tap.test('should compute a score', async () => {
tap.test('should compute a score for a string against the dictionary', async () => {
const result = testSmartfuzzy.getChangeScoreForString('Apple');
console.log(result);
// Check that we got a dictionary map back
expect(result).toBeTypeOf('object');
// Check that every dictionary entry has a score
for (const word of testDictionary) {
expect(result).toHaveProperty(word);
expect(result[word]).toBeTypeofNumber();
}
// Check that 'Apple Inc.' has a lower score (better match) than other entries
expect(result['Apple Inc.']).toBeLessThan(result['Sony']);
});
tap.test('should get closest match', async () => {
tap.test('should get closest match for a string', async () => {
const result = testSmartfuzzy.getClosestMatchForString('Apple');
console.log(result);
// Should return closest match as string
expect(result).toBeTypeofString();
// Should match the expected closest entry
expect(result).toEqual('Apple Inc.');
});
tap.start();
tap.test('should add words to dictionary', async () => {
const initialLength = testSmartfuzzy.dictionary.length;
// Add a single word
testSmartfuzzy.addToDictionary('Microsoft');
expect(testSmartfuzzy.dictionary.length).toEqual(initialLength + 1);
expect(testSmartfuzzy.dictionary).toContain('Microsoft');
// Add multiple words
const additionalWords = ['Google', 'Amazon', 'Facebook'];
testSmartfuzzy.addToDictionary(additionalWords);
expect(testSmartfuzzy.dictionary.length).toEqual(initialLength + 4);
for (const word of additionalWords) {
expect(testSmartfuzzy.dictionary).toContain(word);
}
});
tap.test('should handle empty query string', async () => {
const result = testSmartfuzzy.getClosestMatchForString('');
// For empty strings, behavior should be defined (either null or a specific result)
expect(result).toBeNullOrUndefined();
});
export default tap.start();

8
ts/00_commitinfo_data.ts Normal file
View File

@ -0,0 +1,8 @@
/**
* autocreated commitinfo by @push.rocks/commitinfo
*/
export const commitinfo = {
name: '@push.rocks/smartfuzzy',
version: '1.1.8',
description: 'A library for fuzzy matching strings against word dictionaries or arrays, with support for object and article searching.'
}

View File

@ -1,3 +1,3 @@
export * from './smartfuzzy.articlesearch';
export * from './smartfuzzy.classes.smartfuzzy';
export * from './smartfuzzy.classes.objectsorter';
export * from './smartfuzzy.articlesearch.js';
export * from './smartfuzzy.classes.smartfuzzy.js';
export * from './smartfuzzy.classes.objectsorter.js';

View File

@ -1,4 +1,4 @@
import * as plugins from './smartfuzzy.plugins';
import * as plugins from './smartfuzzy.plugins.js';
/**
* an article search that searches articles in a weighted manner

View File

@ -1,4 +1,4 @@
import * as plugins from './smartfuzzy.plugins';
import * as plugins from './smartfuzzy.plugins.js';
export class ObjectSorter<T> {
public objectDictionary: T[];
@ -7,7 +7,7 @@ export class ObjectSorter<T> {
this.objectDictionary = objectDictionaryArg;
}
sort(stringArg: string, objectKeysArg: string[]): plugins.fuseJs.FuseResult<T>[] {
sort(stringArg: string, objectKeysArg: string[]): Array<{ item: T; refIndex: number; score?: number }> {
const fuseOptions = {
shouldSort: true,
threshold: 0.6,

View File

@ -1,4 +1,4 @@
import * as plugins from './smartfuzzy.plugins';
import * as plugins from './smartfuzzy.plugins.js';
export let standardExport = 'Hi there! :) This is an exported string';

View File

@ -1,5 +1,5 @@
// @pushrocks scope
import * as smartpromise from '@pushrocks/smartpromise';
import * as smartpromise from '@push.rocks/smartpromise';
export { smartpromise };

16
tsconfig.json Normal file
View File

@ -0,0 +1,16 @@
{
"compilerOptions": {
"experimentalDecorators": true,
"useDefineForClassFields": false,
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"verbatimModuleSyntax": true,
"baseUrl": ".",
"paths": {}
},
"exclude": [
"dist_*/**/*.d.ts"
]
}

View File

@ -1,17 +0,0 @@
{
"extends": ["tslint:latest", "tslint-config-prettier"],
"rules": {
"semicolon": [true, "always"],
"no-console": false,
"ordered-imports": false,
"object-literal-sort-keys": false,
"member-ordering": {
"options":{
"order": [
"static-method"
]
}
}
},
"defaultSeverity": "warning"
}