### Install CmpStr
Source: https://github.com/komed3/cmpstr/wiki/FAQ
Use npm to install the CmpStr package.
```bash
npm install cmpstr
```
--------------------------------
### Install CmpStr
Source: https://context7.com/komed3/cmpstr/llms.txt
Install the cmpstr library using npm or yarn.
```sh
npm install cmpstr
# or
yarn add cmpstr
```
--------------------------------
### Basic CmpStr Usage Example
Source: https://github.com/komed3/cmpstr/wiki/API-Reference
Demonstrates creating a CmpStr instance with a specific metric and flags, then performing single, batch, sorted batch, and matrix comparisons.
```typescript
import { CmpStr } from 'cmpstr';
const cmp = CmpStr.create( { metric: 'levenshtein', flags: 'i' } );
const result = cmp.test( 'kITTen', 'Sitting' );
// result: { source: 'kITTen', target: 'Sitting', match: 0.57142… }
const batch = cmp.batchTest( [ 'hello', 'Hallo' ], [ 'hey', 'hola' ] );
// batch: [ { source: 'hello', target: 'hey', match: 0.4 }, … ]
const sorted = cmp.batchSorted( [ 'foo', 'bar' ], [ 'baz', 'foo' ] );
// sorted: [ { source: 'foo', target: 'foo', match: 1 }, … ]
const matrix = cmp.matrix( [ 'foo', 'bar', 'baz' ] );
// matrix: [ [ 1, 0, 0 ], [ 0, 1, 0.666… ], [ 0, 0.666…, 1 ] ]
```
--------------------------------
### Install CmpStr with yarn
Source: https://github.com/komed3/cmpstr/blob/master/README.md
Use this command to install the CmpStr package using yarn.
```sh
yarn add cmpstr
```
--------------------------------
### Example ASCII Diff Output
Source: https://github.com/komed3/cmpstr/wiki/Diff-&-Text-Analysis
This is an example of the output produced by `getASCIIDiff()`, showing insertions and deletions with line numbers and markers.
```text
@@ -2,13 +2,12 @@ +--
1 The quick brown fox
2 - -[jumps] over the lazy dog.
+ +[leaps] over the lazy dog.
3 - This is the -[original] text.
+ This is the +[changed] text.
```
--------------------------------
### Create CmpStr Instance with Options
Source: https://github.com/komed3/cmpstr/wiki/API-Reference
Instantiate CmpStr with specific comparison and matching configurations. This example sets the Levenshtein metric, case-insensitive and trim whitespace flags, and enables removal of zero-similarity results.
```typescript
import { CmpStr } from 'cmpstr';
const cmp = CmpStr.create( {
metric: 'levenshtein',
flags: 'itw',
removeZero: true
} );
```
--------------------------------
### Minimal TextAnalyzer Example
Source: https://github.com/komed3/cmpstr/wiki/Diff-&-Text-Analysis
Demonstrates basic usage of TextAnalyzer by calculating word count, average word length, most common words, readability score, LIX score, and checking for numbers. Requires importing TextAnalyzer from 'cmpstr'.
```typescript
import { TextAnalyzer } from 'cmpstr';
const analyzer = new TextAnalyzer( 'The quick brown fox jumps over the lazy dog. 12345!' );
console.log( analyzer.getWordCount() ); // 9
console.log( analyzer.getAvgWordLength() ); // 3.888…
console.log( analyzer.getMostCommonWords( 3 ) ); // [ 'the', 'quick', 'brown' ]
console.log( analyzer.getReadabilityScore() ); // 98.8675 (Flesch)
console.log( analyzer.getLIXScore() ); // 4.5
console.log( analyzer.hasNumbers() ); // true
```
--------------------------------
### Configure Phonetic Algorithm with Soundex
Source: https://github.com/komed3/cmpstr/wiki/Phonetic-Algorithms
Example of configuring CmpStr to use the Soundex phonetic algorithm with a German mapping and a maximum code length of 6.
```typescript
const cmp = CmpStr.create().setProcessors( {
phonetic: { algo: 'soundex', opt: { map: 'de', length: 6 } }
} );
```
--------------------------------
### Load CmpStr UMD from jsDelivr CDN
Source: https://github.com/komed3/cmpstr/wiki/Installation-&-Setup
Load the UMD bundle directly from the jsDelivr CDN. Useful for quick testing or lightweight integrations without local installation.
```html
```
--------------------------------
### Load CmpStr ESM from jsDelivr CDN
Source: https://github.com/komed3/cmpstr/wiki/Installation-&-Setup
Import the ESM bundle from the jsDelivr CDN in modern browsers. This method avoids local installation and is suitable for rapid prototyping.
```html
```
--------------------------------
### Enable CmpStr Profiler
Source: https://github.com/komed3/cmpstr/wiki/Quick-Start
Activate the built-in profiler to start collecting performance and diagnostic data. The profiler is disabled by default.
```typescript
CmpStr.profiler.enable();
```
--------------------------------
### Extending CmpStr - Custom Phonetic Algorithms & Mappings
Source: https://context7.com/komed3/cmpstr/llms.txt
This section guides you through creating custom phonetic algorithms and mappings for CmpStr. It involves subclassing `Phonetic` and registering mappings with `PhoneticMappingRegistry`.
```APIDOC
## Extending CmpStr — Custom Phonetic Algorithms & Mappings
Subclass `Phonetic` and register a mapping via `PhoneticMappingRegistry`.
```ts
import {
type PhoneticOptions,
Phonetic, PhoneticRegistry, PhoneticMappingRegistry
} from 'cmpstr/root';
import { CmpStr } from 'cmpstr';
// 1. Define and register a phonetic mapping
PhoneticMappingRegistry.add( 'myPhonetic', 'en', {
map: { a: '1', b: '2', c: '3', d: '4' },
patterns: [
{ pattern: /ph/g, replace: 'f' }
],
ruleset: [
{ char: 'c', next: [ 'e', 'i', 'y' ], code: 'S' } // c before e/i/y → S
],
ignore: [ 'h', 'w' ],
options: { length: 4, pad: '0', dedupe: true }
} );
// 2. Subclass Phonetic
class MyPhonetic extends Phonetic {
protected static override default: PhoneticOptions = {
map: 'en', delimiter: ' ', length: 4, pad: '0', dedupe: true
};
constructor( opt: PhoneticOptions = {} ) {
super( 'myPhonetic', opt );
}
}
// 3. Register and use
PhoneticRegistry.add( 'myPhonetic', MyPhonetic );
const cmp = CmpStr.create( { metric: 'dice' } )
.setProcessors( { phonetic: { algo: 'myPhonetic', opt: { map: 'en' } } } );
cmp.compare( 'abc', 'abcd' ); // compared via phonetic codes
```
```
--------------------------------
### Creating a CmpStr Instance
Source: https://github.com/komed3/cmpstr/wiki/API-Reference
Demonstrates how to create a new CmpStr instance using the static `create()` method with optional configuration.
```APIDOC
## Creating a CmpStr Instance
A new `CmpStr` instance is created using the static `create()` method. This method accepts an optional configuration object or a serialized configuration string, which defines the initial behavior of all comparison and matching operations.
```ts
import { CmpStr } from 'cmpstr';
const cmp = CmpStr.create( {
metric: 'levenshtein',
flags: 'itw',
removeZero: true
} );
```
If no configuration is provided, default values are applied. The instance configuration can be modified at any time using the available configuration methods.
```
--------------------------------
### Instantiation
Source: https://github.com/komed3/cmpstr/wiki/Asynchronous-API
Instances of the asynchronous CmpStr API are created using the `create` method, similar to the synchronous API. Options can be passed during creation or managed via inherited methods.
```APIDOC
## Instantiation
Instances are created in the same way as with the synchronous API:
```ts
const cmpAsync = CmpStrAsync.create( options? );
```
All configuration and option management methods (`setOptions`, `mergeOptions`, `setOption`, `getOptions`, etc.) are inherited from `CmpStr` and behave identically. Instance-level options can be overridden per call without affecting global state.
```
--------------------------------
### Asynchronously Get Phonetic Index
Source: https://github.com/komed3/cmpstr/wiki/Asynchronous-API
Determines the phonetic index for a given string using a specified algorithm.
```typescript
phoneticIndexAsync ( input: string, algo?: string, opt?: PhoneticOptions ) : Promise< string >
```
--------------------------------
### Asynchronously Get Similarity Score
Source: https://github.com/komed3/cmpstr/wiki/Asynchronous-API
Performs an asynchronous string comparison and resolves only to the normalized similarity score (0 to 1).
```typescript
compareAsync ( a: string, b: string, opt? ) : Promise< number >
```
--------------------------------
### Accessing Development Entry Point
Source: https://github.com/komed3/cmpstr/wiki/Extending-CmpStr
Use the dedicated development entry point to import necessary base classes, registries, and utilities for custom extensions. This keeps the default bundle lightweight.
```typescript
const { ... } = require( 'cmpstr/root' );
```
```typescript
import { ... } from 'cmpstr/root';
```
--------------------------------
### Configuration Methods
Source: https://github.com/komed3/cmpstr/wiki/API-Reference
Methods for fine-grained control over similarity metrics, normalization, and preprocessing. All methods are chainable and return the instance (`this`).
```APIDOC
## setMetric ( name: string ) : this
Sets the similarity metric. The name must correspond to a registered metric identifier.
```
```APIDOC
## setFlags ( flags: NormalizeFlags ) : this
Defines normalization flags. Multiple flags can be combined.
```
```APIDOC
## rmvFlags () : this
Removes all normalization flags.
```
```APIDOC
## setProcessors ( processors: CmpStrProcessors ) : this
Configures preprocessing steps such as phonetic algorithms.
```
```APIDOC
## rmvProcessors () : this
Removes all configured preprocessors.
```
```APIDOC
## setRaw ( enable: boolean ) : this
If activated, CmpStr methods return structured raw data (including the raw data from the used metric).
```
--------------------------------
### Compare Two Strings
Source: https://github.com/komed3/cmpstr/wiki/API-Reference
Perform a single string comparison and get a structured result including similarity score and raw metric data if enabled.
```typescript
test ( a: string, b: string, opt? ) : ResultLike
```
--------------------------------
### Configuration Management Methods
Source: https://github.com/komed3/cmpstr/wiki/API-Reference
Lists and describes methods for managing the CmpStr instance's configuration.
```APIDOC
## Managing the Configuration
- `setOptions ( options: CmpStrOptions ) : this`
Replaces the entire configuration object.
- `mergeOptions ( options: CmpStrOptions ) : this`
Merges the provided values into the existing configuration. This is the recommended method for partial updates.
- `setOption ( path: string, value: any ) : this`
Updates a single configuration value using a dot-separated path (for example, `processors.phonetic`).
- `setSerializedOptions ( json: string ) : this`
Loads a JSON string and applies it as the new configuration.
- `rmvOption ( path: string ) : this`
Removes a specific option from the configuration.
- `getOptions () : CmpStrOptions`
Returns the complete current configuration object.
- `getOption ( path: string ) : any`
Retrieves the value at the specified configuration path.
- `getSerializedOptions () : string`
Returns the current configuration as a serialized JSON string.
- `reset () : this`
Resets the instance to its default configuration.
- `clone () : CmpStr`
Creates a shallow copy of the instance, including its current configuration.
```
--------------------------------
### Create CmpStr Instance
Source: https://context7.com/komed3/cmpstr/llms.txt
Instantiate CmpStr using the static create() factory. Configuration options can be provided inline, through fluent chaining, or by serializing/deserializing JSON.
```ts
import { CmpStr } from 'cmpstr';
// Inline options
const cmp = CmpStr.create( {
metric: 'levenshtein',
flags: 'itw', // case-insensitive, trim, collapse whitespace
removeZero: true // drop zero-score results from batch operations
} );
// Fluent chaining
const cmp2 = CmpStr.create()
.setMetric( 'dice' )
.setFlags( 'i' )
.setProcessors( { phonetic: { algo: 'soundex' } } )
.setRaw( true );
// Clone an existing instance
const cmp3 = cmp.clone();
// Reset to defaults
cmp3.reset();
// Serialize / restore configuration
const json = cmp.getSerializedOptions();
const cmp4 = CmpStr.create().setSerializedOptions( json );
```
--------------------------------
### Instantiate TextAnalyzer
Source: https://github.com/komed3/cmpstr/wiki/Diff-&-Text-Analysis
Import and create a new TextAnalyzer instance with the text to be analyzed. Ensure the TextAnalyzer class is imported from the 'cmpstr' package.
```typescript
import { TextAnalyzer } from 'cmpstr';
const analyzer = new TextAnalyzer(`'This is a sample text. It contains several sentences.' );
```
--------------------------------
### Configure CmpStr Instance
Source: https://github.com/komed3/cmpstr/wiki/API-Reference
Set Levenshtein metric, case-insensitive flags, Soundex phonetic preprocessing, and raw output mode for detailed comparison results.
```typescript
const cmp = CmpStr.create()
.setMetric( 'levenshtein' )
.setFlags( 'i' )
.setProcessors( { phonetic: { algo: 'soundex' } } )
.setRaw( true );
```
--------------------------------
### String Normalization with Normalizer Class
Source: https://context7.com/komed3/cmpstr/llms.txt
Shows how to preprocess strings using the `Normalizer` class with various flags for decomposition, case conversion, character filtering, and whitespace handling. Supports both single string and batch normalization.
```typescript
import { Normalizer } from 'cmpstr';
// Available flags:
// d – NFD decomposition i – lowercase k – letters only
// n – numbers only r – remove doubles s – remove punctuation
// t – trim whitespace u – NFC composition w – collapse whitespace
// x – NFKC composition
const result = Normalizer.normalize( ' Café Müller!! ', 'ditws' );
// 'cafe muller'
// Batch normalization
const batch = Normalizer.normalize( [ ' Hello ', ' WORLD ', 'foo' ], 'it' );
// [ 'hello', 'world', 'foo' ]
// Async batch normalization
const asyncBatch = await Normalizer.normalizeAsync(
[ 'Hallo', ' hELLo', 'hey ', ' HolA ' ],
'iwt'
);
// [ 'hallo', 'hello', 'hey', 'hola' ]
// Use normalization flags inline on any CmpStr instance
const cmp = CmpStr.create( { flags: 'itws' } );
cmp.compare( ' Héllo ', 'hello' ); // treats both as 'hello' → 1.0
```
--------------------------------
### Perform Structured Lookup Comparison
Source: https://github.com/komed3/cmpstr/wiki/Structured-Data
Use structuredLookup for batch comparisons against a dataset using a specified property. Ensure the CmpStr instance is configured with a metric. This example demonstrates comparing a query string against the 'name' property of objects in an array.
```typescript
import { CmpStr } from 'cmpstr';
const cmp = CmpStr.create( { metric: 'levenshtein' } );
const res = cmp.structuredLookup( 'Mayer', [
{ id: '1', name: 'Meyer' }, { id: '2', name: 'Miller' },
{ id: '3', name: 'Müller' }, { id: '4', name: 'Meier' }
], 'name' );
```
--------------------------------
### CmpStr.create()
Source: https://context7.com/komed3/cmpstr/llms.txt
Factory method to create a configured CmpStr instance. Options can be provided inline, via JSON string, or through fluent chaining.
```APIDOC
## CmpStr.create()
### Description
Factory method that returns a fully configured `CmpStr` instance. Accepts an optional options object or JSON string. All configuration methods are chainable and return `this`.
### Method
`static create(options?: object | string): CmpStr`
### Parameters
#### Options Object
- **metric** (string) - Optional - The similarity metric to use (e.g., 'levenshtein', 'dice').
- **flags** (string) - Optional - Configuration flags for normalization (e.g., 'i' for case-insensitive, 't' for trim, 'w' for collapse whitespace).
- **removeZero** (boolean) - Optional - If true, drops zero-score results from batch operations.
- **processors** (object) - Optional - Configuration for phonetic or other preprocessors.
### Request Example
```ts
import { CmpStr } from 'cmpstr';
// Inline options
const cmp = CmpStr.create( {
metric: 'levenshtein',
flags: 'itw', // case-insensitive, trim, collapse whitespace
removeZero: true // drop zero-score results from batch operations
} );
// Fluent chaining
const cmp2 = CmpStr.create()
.setMetric( 'dice' )
.setFlags( 'i' )
.setProcessors( { phonetic: { algo: 'soundex' } } )
.setRaw( true );
// Clone an existing instance
const cmp3 = cmp.clone();
// Reset to defaults
cmp3.reset();
// Serialize / restore configuration
const json = cmp.getSerializedOptions();
const cmp4 = CmpStr.create().setSerializedOptions( json );
```
```
--------------------------------
### Instantiate CmpStrAsync
Source: https://github.com/komed3/cmpstr/wiki/Asynchronous-API
Create an instance of the asynchronous CmpStr API. Options can be provided during creation.
```typescript
const cmpAsync = CmpStrAsync.create( options? );
```
--------------------------------
### Minimal CmpStr Usage
Source: https://github.com/komed3/cmpstr/blob/master/README.md
Demonstrates the basic creation and usage of CmpStr with a specified metric and flags for string comparison.
```typescript
import { CmpStr } from 'cmpstr';
const cmp = CmpStr.create().setMetric( 'levenshtein' ).setFlags( 'i' );
const result = cmp.test( [ 'hello', 'hola' ], 'Hallo' );
console.log( result );
// { source: 'hello', target: 'Hallo', match: 0.8 }
```
--------------------------------
### Asynchronous CmpStr Usage
Source: https://github.com/komed3/cmpstr/blob/master/README.md
Shows how to use CmpStr asynchronously, setting up phonetic processors and performing a search operation.
```typescript
import { CmpStrAsync } from 'cmpstr';
const cmp = CmpStrAsync.create().setProcessors( {
phonetic: { algo: 'soundex' }
} );
const result = await cmp.searchAsync( 'Maier', [
'Meyer', 'Müller', 'Miller', 'Meyers', 'Meier'
] );
console.log( result );
// [ 'Meyer', 'Meier' ]
```
--------------------------------
### Instantiate DiffChecker
Source: https://github.com/komed3/cmpstr/wiki/Diff-&-Text-Analysis
Import and create a DiffChecker instance to compare two texts. Configure diffing mode (e.g., 'word') and context lines. Ensure DiffChecker is imported from 'cmpstr'.
```typescript
import { DiffChecker } from 'cmpstr';
const a = `The quick brown fox
jumps over the lazy dog.
This is the original text.`;
const b = `The quick brown fox
leaps over the lazy dog.
This is the changed text.`;
const diff = new DiffChecker( a, b, { mode: 'word', contextLines: 1 } );
```
--------------------------------
### Async String Comparison and Batch/Matrix Operations
Source: https://github.com/komed3/cmpstr/wiki/Asynchronous-API
Demonstrates creating an asynchronous CmpStr instance and performing single string tests, batch tests, and generating a similarity matrix. All methods return Promises and are designed for async/await usage.
```typescript
import { CmpStrAsync } from 'cmpstr';
const cmp = CmpStrAsync.create( { metric: 'levenshtein', flags: 'i' } );
const result = await cmp.testAsync( 'kITTen', 'Sitting' );
// result: { source: 'kITTen', target: 'Sitting', match: 0.57142… }
const batch = await cmp.batchTestAsync( [ 'hello', 'Hallo' ], [ 'hey', 'hola' ] );
// batch: [ { source: 'hello', target: 'hey', match: 0.4 }, … ]
const matrix = await cmp.matrixAsync( [ 'foo', 'bar', 'baz' ] );
// matrix: [ [ 1, 0, 0 ], [ 0, 1, 0.666… ], [ 0, 0.666…, 1 ] ]
```
--------------------------------
### String Similarity Metrics in CmpStr
Source: https://context7.com/komed3/cmpstr/llms.txt
Demonstrates how to use CmpStr's `create` method with various `metric` options to compare strings. Each metric returns a normalized score between 0 and 1. Ensure the correct metric ID is used.
```typescript
import { CmpStr } from 'cmpstr';
// Levenshtein (edit distance)
CmpStr.create( { metric: 'levenshtein' } ).compare( 'kitten', 'sitting' ); // 0.5714…
// Damerau-Levenshtein (transpositions count as 1 edit)
CmpStr.create( { metric: 'damerau' } ).compare( 'teh', 'the' ); // 0.666…
// Jaro-Winkler (optimized for short strings / names)
CmpStr.create( { metric: 'jaroWinkler' } ).compare( 'MARTHA', 'MARHTA' ); // 0.9611…
// Dice-Sørensen (bigram overlap)
CmpStr.create( { metric: 'dice' } ).compare( 'night', 'nacht' ); // 0.25
// Jaccard (set overlap — characters or tokens)
CmpStr.create( { metric: 'jaccard' } ).compare( 'abc', 'abcd' ); // 0.75
// Cosine (vector angle, word-level by default)
CmpStr.create( { metric: 'cosine' } ).compare(
'the cat sat on the mat',
'the cat sat on a mat'
); // ~0.971
// Hamming (positional mismatches; equal-length strings)
CmpStr.create( { metric: 'hamming' } ).compare( 'karolin', 'kathrin' ); // 0.571…
// LCS (longest common subsequence)
CmpStr.create( { metric: 'lcs' } ).compare( 'ABCBDAB', 'BDCABA' ); // 0.571…
// Needleman-Wunsch (global alignment, configurable penalties)
CmpStr.create( { metric: 'needlemanWunsch' } ).compare( 'GCATGCU', 'GATTACA' );
// Smith-Waterman (local alignment)
CmpStr.create( { metric: 'smithWaterman' } ).compare( 'ACACACTA', 'AGCACACA' );
// q-Gram (overlapping substrings of length q)
CmpStr.create( { metric: 'qGram' } ).compare( 'night', 'nacht' ); // ~0.333
```
```typescript
// List all registered metric IDs
CmpStr.metric.list();
// [ 'levenshtein', 'damerau', 'jaroWinkler', 'dice', 'jaccard',
// 'cosine', 'hamming', 'lcs', 'needlemanWunsch', 'smithWaterman', 'qGram' ]
```
--------------------------------
### Configure Phonetic Algorithm with Mapping
Source: https://github.com/komed3/cmpstr/wiki/FAQ
When using a phonetic algorithm like Soundex, ensure a valid map option is provided for language-specific processing.
```typescript
cmp.setProcessors( { phonetic: { algo: 'soundex', opt: { map: 'en' } } } );
```
--------------------------------
### Override Options for a Single Call
Source: https://github.com/komed3/cmpstr/wiki/API-Reference
Demonstrates how to use instance-level options for a default comparison and then override specific options for a single method call. This allows for flexible, per-operation adjustments without altering the global configuration.
```typescript
cmp.test( 'apple', 'Apfel' ); // uses global options
cmp.test( 'apple', 'Apfel', { flags: 'i' } ); // overrides flags locally for this call
```
--------------------------------
### List Available Phonetic Algorithms and Mappings in CmpStr
Source: https://github.com/komed3/cmpstr/wiki/Phonetic-Algorithms
Inspect the phonetic algorithms and their available mappings supported by CmpStr. This is useful for understanding which algorithms can be used.
```typescript
CmpStr.phonetic.list(); // [ 'soundex', 'cologne', 'metaphone', 'caverphone' ]
```
```typescript
CmpStr.phonetic.map.list( 'soundex' ); // [ 'en', 'de' ]
```
--------------------------------
### Asynchronous String Comparison with CmpStrAsync
Source: https://context7.com/komed3/cmpstr/llms.txt
Demonstrates various asynchronous comparison methods including single, batch, matrix, phonetic search, and structured lookup. Requires `CmpStrAsync` instantiation with specified metrics and flags.
```typescript
import { CmpStrAsync } from 'cmpstr';
const cmp = CmpStrAsync.create( { metric: 'levenshtein', flags: 'i' } );
// Async single comparison
const result = await cmp.testAsync( 'kITTen', 'Sitting' );
// { source: 'kITTen', target: 'Sitting', match: 0.5714… }
// Async score only
const score = await cmp.compareAsync( 'hello', 'Hallo' );
// 0.8
// Async batch
const batch = await cmp.batchTestAsync( [ 'hello', 'Hallo' ], [ 'hey', 'hola' ] );
// Async similarity matrix
const matrix = await cmp.matrixAsync( [ 'foo', 'bar', 'baz' ] );
// Async phonetic search — returns matching strings from haystack
const hits = await cmp.searchAsync(
'Maier',
[ 'Meyer', 'Müller', 'Miller', 'Meyers', 'Meier' ],
'i',
{ phonetic: { algo: 'soundex' } }
);
// [ 'Meyer', 'Meier' ]
// Async structured lookup
const contacts = [
{ id: '1', name: 'Meyer' },
{ id: '2', name: 'Meier' }
];
const structured = await cmp.structuredLookupAsync( 'Mayer', contacts, 'name' );
```
--------------------------------
### Extending CmpStr - Custom Metrics
Source: https://context7.com/komed3/cmpstr/llms.txt
Learn how to extend CmpStr by creating your own custom comparison metrics. This involves subclassing the `Metric` class and registering it with the `MetricRegistry`.
```APIDOC
## Extending CmpStr — Custom Metrics
Subclass `Metric` from `cmpstr/root` and register under a unique ID.
```ts
import {
type MetricInput, type MetricOptions, type MetricCompute,
Metric, MetricRegistry
} from 'cmpstr/root';
import { CmpStr } from 'cmpstr';
class ExactMatch extends Metric {
constructor( a: MetricInput, b: MetricInput, opt: MetricOptions = {} ) {
super( 'exactMatch', a, b, opt, true ); // true = symmetric
}
protected override compute(
a: string, b: string,
m: number, n: number,
maxLen: number
): MetricCompute<{}> {
return { res: a === b ? 1 : 0 };
}
}
MetricRegistry.add( 'exactMatch', ExactMatch );
const cmp = CmpStr.create( { metric: 'exactMatch' } );
cmp.compare( 'hello', 'hello' ); // 1
cmp.compare( 'hello', 'world' ); // 0
```
```
--------------------------------
### Static Utilities
Source: https://github.com/komed3/cmpstr/wiki/API-Reference
Provides static methods for text inspection, diffing, and managing global registries.
```APIDOC
## CmpStr.analyze
### Description
Returns a `TextAnalyzer` instance that provides structural information about the input string.
### Parameters
- **input** (string) - Required - The string to analyze.
### Returns
(TextAnalyzer) - An instance of TextAnalyzer.
```
```APIDOC
## CmpStr.diff
### Description
Returns a `DiffChecker` instance for creating unified text diffs between two strings.
### Parameters
- **a** (string) - Required - The first string.
- **b** (string) - Required - The second string.
- **opt** (DiffOptions) - Optional - Options to customize the diff algorithm.
### Returns
(DiffChecker) - An instance of DiffChecker.
```
```APIDOC
## CmpStr.filter
### Description
Static interface for global normalization filter management. Allows adding, removing, pausing, resuming, listing, and clearing filters.
### Methods
- **has(id)**: Checks if a filter exists.
- **add(id, processor)**: Adds a new filter.
- **remove(id)**: Removes a filter.
- **pause(id)**: Pauses a filter.
- **resume(id)**: Resumes a filter.
- **list()**: Lists all active filters.
- **clear()**: Clears all filters.
```
```APIDOC
## CmpStr.metric
### Description
Static interface to the global metric registry. Provides the ability to add, remove, check existence, and list registered similarity metrics.
### Methods
- **add(id, metric)**: Registers a new metric.
- **remove(id)**: Removes a metric.
- **has(id)**: Checks if a metric exists.
- **list()**: Lists all registered metric identifiers.
```
```APIDOC
## CmpStr.phonetic
### Description
Static access to the phonetic registry and mapping management. Allows registering new phonetic algorithms, retrieving available options, and modifying algorithm behavior globally.
### Methods
- **add(id, algorithm)**: Registers a new phonetic algorithm.
- **remove(id)**: Removes a phonetic algorithm.
- **has(id)**: Checks if a phonetic algorithm exists.
- **list()**: Lists all registered phonetic algorithm identifiers.
```
```APIDOC
## CmpStr.profiler
### Description
Provides static access to global profiling and benchmarking services for analyzing performance of normalization, comparison, or processing steps.
```
```APIDOC
## CmpStr.clearCache
### Description
Clears internal caches used by the normalizer, metric system, and phonetic processor modules. Useful for development, debugging, or dynamic updates.
```
--------------------------------
### Batch String Comparison
Source: https://context7.com/komed3/cmpstr/llms.txt
Perform batch comparisons using batchTest() for all combinations or batchSorted() for sorted results. Options like 'raw' and sorting order ('asc'/'desc') are supported.
```ts
import { CmpStr } from 'cmpstr';
const cmp = CmpStr.create( { metric: 'levenshtein', flags: 'i' } );
const results = cmp.batchTest( [ 'hello', 'hola' ], 'Hallo' );
/**
* [
* { source: 'hello', target: 'Hallo', match: 0.8 },
* { source: 'hola', target: 'Hallo', match: 0.4 }
* ]
*/
// With raw metric data
const raw = cmp.batchTest( [ 'hello', 'hola' ], 'Hallo', { raw: true } );
/**
* [
* { metric: 'levenshtein', a: 'hello', b: 'Hallo', res: 0.8, raw: { dist: 1, maxLen: 5 } },
* { metric: 'levenshtein', a: 'hola', b: 'Hallo', res: 0.4, raw: { dist: 3, maxLen: 5 } }
* ]
*/
// Sorted descending (default)
const sorted = cmp.batchSorted( [ 'foo', 'bar', 'baz' ], [ 'baz', 'foo' ] );
// [ { source: 'foo', target: 'foo', match: 1 }, … ]
// Sorted ascending
const asc = cmp.batchSorted( [ 'foo', 'bar' ], [ 'baz', 'foo' ], 'asc' );
```
--------------------------------
### Create StructuredData Instance
Source: https://github.com/komed3/cmpstr/wiki/Structured-Data
Instantiate the generic StructuredData class using the create factory method. Provide the dataset and the key property for comparison. The instance stores references without immediate preprocessing.
```typescript
StructuredData.create( data, key )
```
--------------------------------
### Phonetic and Text Utilities
Source: https://github.com/komed3/cmpstr/wiki/Asynchronous-API
Asynchronous methods for generating phonetic indexes and performing substring searches.
```APIDOC
## Phonetic and Text Utilities
- `phoneticIndexAsync ( input: string, algo?: string, opt?: PhoneticOptions ) : Promise< string >`
Asynchronous method for determining phonetic indexes of given strings.
- `searchAsync ( needle: string, haystack: string[], flags?: NormalizeFlags, processors?: CmpStrProcessors ) : Promise< string[] >`
Performs an asynchronous filtered and normalized substring search across the `haystack` array.
```
--------------------------------
### Use CmpStr UMD Bundle in Browser
Source: https://github.com/komed3/cmpstr/wiki/Installation-&-Setup
Include the UMD bundle script for maximum browser compatibility or in projects without a bundler. This exposes CmpStr globally.
```html
```
--------------------------------
### Per-Call Options Override
Source: https://github.com/komed3/cmpstr/wiki/API-Reference
Illustrates how to temporarily override instance-level configuration for a specific method call.
```APIDOC
## Per-Call Options Override
In addition to the instance-level configuration, most methods accept an optional per-call options object. These values temporarily override the instance configuration for that specific invocation without modifying the global state.
```ts
cmp.test( 'apple', 'Apfel' ); // uses global options
cmp.test( 'apple', 'Apfel', { flags: 'i' } ); // overrides flags locally for this call
```
```
--------------------------------
### Basic String Comparison
Source: https://github.com/komed3/cmpstr/wiki/API-Reference
Compares two strings using the configured metric and returns a structured result object.
```APIDOC
## test
### Description
Compares two strings and returns a structured result object containing the source string, target string, and a match score.
### Method
`test(source: string | string[], target: string | string[], options?: CmpStrOptions): CmpStrResult | CmpStrResult[]`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```ts
const cmp = CmpStr.create( { metric: 'levenshtein', flags: 'i' } );
const result = cmp.test( 'kITTen', 'Sitting' );
// result: { source: 'kITTen', target: 'Sitting', match: 0.57142… }
```
### Response
#### Success Response (200)
- **source** (string) - The original source string.
- **target** (string) - The original target string.
- **match** (number) - The similarity score between the source and target strings.
#### Response Example
```json
{
"source": "kITTen",
"target": "Sitting",
"match": 0.5714285714285714
}
```
```
--------------------------------
### test() / compare()
Source: https://context7.com/komed3/cmpstr/llms.txt
Compares two strings. `test()` returns a structured result object, while `compare()` returns only the normalized similarity score.
```APIDOC
## test() / compare()
### Description
`test()` compares two strings and returns a `{ source, target, match }` result object. `compare()` returns only the normalized similarity score (`0..1`).
### Methods
- `test(source: string, target: string, options?: object): { source: string, target: string, match: number }`
- `compare(source: string, target: string, options?: object): number`
### Parameters
#### Path Parameters
- **source** (string) - Required - The first string to compare.
- **target** (string) - Required - The second string to compare.
- **options** (object) - Optional - Per-call option overrides. `raw` (boolean) can be set to true to include raw metric data.
### Request Example
```ts
import { CmpStr } from 'cmpstr';
const cmp = CmpStr.create( { metric: 'levenshtein', flags: 'i' } );
// Structured result
const result = cmp.test( 'kITTen', 'Sitting' );
// { source: 'kITTen', target: 'Sitting', match: 0.5714… }
// Score only
const score = cmp.compare( 'hello', 'Hallo' );
// 0.8
// Per-call option override (does not affect global config)
const rawResult = cmp.test( 'hello', 'Hallo', { raw: true } );
// { metric: 'levenshtein', a: 'hello', b: 'Hallo', res: 0.8, raw: { dist: 1, maxLen: 5 } }
```
```
--------------------------------
### Add Custom Mappings to Built-in Algorithms
Source: https://github.com/komed3/cmpstr/wiki/Extending-CmpStr
Extend existing built-in phonetic algorithms, such as 'soundex', by adding new language-specific mappings. This is useful for supporting new languages or algorithm variations.
```typescript
PhoneticMappingRegistry.add( 'soundex', 'fr', {
map: { a: '0', b: '1', ... }, // ...patterns, ruleset, options
} );
```
--------------------------------
### Common Configuration Fields
Source: https://github.com/komed3/cmpstr/wiki/API-Reference
Describes frequently used configuration fields for customizing CmpStr behavior.
```APIDOC
## Common Configuration Fields
Some of the most commonly used configuration keys include:
- `metric` Specifies the [similarity algorithm](./Similarity-Metrics) to use (e.g., `levenshtein`, `jaroWinkler`, `dice`).
- `flags` A string controlling [normalization behavior](./Normalization-&-Filtering) (e.g., `i` for case-insensitive, `d` to remove numbers).
- `processors` Defines additional preprocessing steps, including [phonetic mappings](./Phonetic-Algorithms).
- `raw` If enabled, methods return detailed result structures including raw metric data.
- `removeZero` If enabled, batch operations filter out results with a similarity score of `0`.
- `output` Controls whether result values reflect the original input (`orig`) or the normalized representation (`prep`).
- `safeEmpty` If enabled, empty input values return empty results instead of throwing errors.
By combining these options, CmpStr can be adapted to a wide range of matching and comparison scenarios with minimal configuration overhead.
```
--------------------------------
### Custom Filtering Pipeline with CmpStr.filter
Source: https://context7.com/komed3/cmpstr/llms.txt
Illustrates how to add, pause, resume, remove, and list custom preprocessing filters for the 'input' hook using `CmpStr.filter`. Filters are applied after normalization and support priority ordering.
```typescript
import { CmpStr } from 'cmpstr';
// Register a filter on the 'input' hook
CmpStr.filter.add(
'input',
'digits2Asterix',
( s: string ) => s.replace( /\d+/g, '*' ),
{ priority: 5 }
);
const cmp = CmpStr.create( { metric: 'levenshtein' } );
console.log( cmp.compare( 'abc123', 'abc*' ) ); // both become 'abc*' → 1.0
// Pause (deactivate) without removing
CmpStr.filter.pause( 'input', 'digits2Asterix' );
// Resume
CmpStr.filter.resume( 'input', 'digits2Asterix' );
// Remove permanently
CmpStr.filter.remove( 'input', 'digits2Asterix' );
// List active filters for a hook
const active = CmpStr.filter.list( 'input', true );
// Clear all filters for a hook, or globally
CmpStr.filter.clear( 'input' );
CmpStr.filter.clear();
```
--------------------------------
### Implementing a Custom Phonetic Algorithm
Source: https://github.com/komed3/cmpstr/wiki/Extending-CmpStr
Extend the `Phonetic` base class to create custom phonetic algorithms. Set default options using the static `default` property and call the parent constructor.
```typescript
import {
type PhoneticOptions,
Phonetic, PhoneticRegistry, PhoneticMappingRegistry
} from 'cmpstr/root';
class MyPhonetic extends Phonetic {
protected static override default: PhoneticOptions = {
map: 'en', delimiter: ' ', length: 4, pad: '0', dedupe: true
};
constructor ( opt: PhoneticOptions = {} ) {
super( 'myPhonetic', opt );
}
}
```
--------------------------------
### Phonetic-Aware Comparison with setProcessors()
Source: https://context7.com/komed3/cmpstr/llms.txt
Attach a phonetic preprocessor to enable all comparison methods to operate on phonetic codes. This is useful for fuzzy matching based on pronunciation.
```typescript
import { CmpStr } from 'cmpstr';
// Cologne phonetics for German names
const cmp = CmpStr.create( { metric: 'levenshtein' } )
.setProcessors( { phonetic: { algo: 'cologne' } } );
const results = cmp.batchTest(
'Maier',
[ 'Meyer', 'Müller', 'Miller', 'Meyers', 'Meier' ]
);
/**
* Names that share the Cologne code with "Maier" will score high,
* e.g. Meyer (67) and Meier (67) both encode to the same code.
*/
// Metaphone for English-language fuzzy matching
const cmp2 = CmpStr.create( { metric: 'dice' } )
.setProcessors( { phonetic: { algo: 'metaphone' } } );
const score = cmp2.compare( 'knight', 'night' );
// Both reduce to the same Metaphone code → 1.0
```
--------------------------------
### Batch String Comparison
Source: https://github.com/komed3/cmpstr/wiki/API-Reference
Compares multiple source strings against multiple target strings, returning an array of structured results.
```APIDOC
## batchTest
### Description
Compares each string in the source array against each string in the target array, returning an array of structured comparison results.
### Method
`batchTest(source: string[], target: string[], options?: CmpStrOptions): CmpStrResult[]`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```ts
const cmp = CmpStr.create( { metric: 'levenshtein', flags: 'i' } );
const batch = cmp.batchTest( [ 'hello', 'Hallo' ], [ 'hey', 'hola' ] );
// batch: [ { source: 'hello', target: 'hey', match: 0.4 }, { source: 'hello', target: 'hola', match: 0.6 }, { source: 'Hallo', target: 'hey', match: 0.4 }, { source: 'Hallo', target: 'hola', match: 0.6 } ]
```
### Response
#### Success Response (200)
- **Array of CmpStrResult objects**: Each object contains `source`, `target`, and `match` properties for a single comparison.
#### Response Example
```json
[
{
"source": "hello",
"target": "hey",
"match": 0.4
},
{
"source": "hello",
"target": "hola",
"match": 0.6
}
]
```
```
--------------------------------
### Threshold & Top-N Queries with match(), closest(), furthest()
Source: https://context7.com/komed3/cmpstr/llms.txt
Filter results by a minimum score threshold or retrieve the top/bottom N matches. Ensure the CmpStr library is imported and initialized with a metric and flags.
```typescript
import { CmpStr } from 'cmpstr';
const cmp = CmpStr.create( { metric: 'dice', flags: 'i' } );
const candidates = [ 'apple', 'application', 'apply', 'banana', 'mango' ];
// Only results with score ≥ 0.5
const matched = cmp.match( 'appl', candidates, 0.5 );
/**
* [
* { source: 'appl', target: 'apply', match: 0.666… },
* { source: 'appl', target: 'apple', match: 0.571… },
* { source: 'appl', target: 'application', match: 0.5 }
* ]
*/
// Best 2 matches
const top2 = cmp.closest( 'appl', candidates, 2 );
// [ { source: 'appl', target: 'apply', match: 0.666… }, … ]
// Worst 2 matches
const bottom2 = cmp.furthest( 'appl', candidates, 2 );
```