-
-
Notifications
You must be signed in to change notification settings - Fork 1
API Reference
This page provides a structured reference for the CmpStr class and its public API. Each method is documented with its purpose, expected parameters, return values, and typical usage patterns. All instance methods are accessed through a CmpStr instance, which is created using the static CmpStr.create() factory method.
The API is designed to be consistent, predictable, and fully type-safe. Both synchronous and asynchronous variants follow the same conceptual model and naming conventions.
Use this reference when integrating CmpStr into your application or when extending the library with custom functionality.
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.
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.
All configuration in CmpStr is managed through a single options object. These options define the default behavior of core methods such as .test(), .match(), .compare(), and related batch operations.
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.
cmp.test( 'apple', 'Apfel' ); // uses global options
cmp.test( 'apple', 'Apfel', { flags: 'i' } ); // overrides flags locally for this callInternally, options are deeply merged and accessed via dot-separated paths, allowing flexible and targeted updates of nested configuration fields.
-
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.
Some of the most commonly used configuration keys include:
-
metricSpecifies the similarity algorithm to use (e.g.,levenshtein,jaroWinkler,dice). -
flagsA string controlling normalization behavior (e.g.,ifor case-insensitive,dto remove numbers). -
processorsDefines additional preprocessing steps, including phonetic mappings. -
rawIf enabled, methods return detailed result structures including raw metric data. -
removeZeroIf enabled, batch operations filter out results with a similarity score of0. -
outputControls whether result values reflect the original input (orig) or the normalized representation (prep). -
safeEmptyIf 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.
For fine-grained control over similarity metrics, normalization, and preprocessing behavior, CmpStr exposes dedicated configuration methods. All methods in this group are chainable and return the instance (this), allowing compact and readable setup sequences.
const cmp = CmpStr.create()
.setMetric( 'levenshtein' )
.setFlags( 'i' )
.setProcessors( { phonetic: { algo: 'soundex' } } )
.setRaw( true );In this example, comparisons are performed using the Levenshtein distance, case-insensitive normalization, Soundex-based phonetic preprocessing, and detailed raw output.
Available methods include:
-
setMetric ( name: string ) : this
Sets the similarity metric. The name must correspond to a registered metric identifier. -
setFlags ( flags: NormalizeFlags ) : this
Defines normalization flags. Multiple flags can be combined. -
rmvFlags () : this
Removes all normalization flags. -
setProcessors ( processors: CmpStrProcessors ) : this
Configures preprocessing steps such as phonetic algorithms. -
rmvProcessors () : this
Removes all configured preprocessors. -
setRaw ( enable: boolean ) : this
If activated, CmpStr methods return structured raw data (including the raw data from the used metric).
This targeted configuration model allows precise control without requiring a full options object for each operation.
The CmpStr class provides multiple comparison modes ranging from single comparisons to batch and matrix-based operations. All methods follow a consistent interface and respect the current instance configuration, which can be overridden per call.
Each comparison method accepts the following parameters:
-
aSource input — a string or an array of strings. -
bTarget input — a string or an array of strings. -
opt(optional) A configuration object overriding instance options for this call.
These methods are used to compare two individual strings:
-
test ( a: string, b: string, opt? ) : ResultLike
Compares two strings and returns a structured result containing the source, target, and similarity score. Whenrawmode is enabled, additional metric-specific data is included. -
compare ( a: string, b: string, opt? ) : number
Performs the same comparison as test but returns only the normalized similarity score (0..1).
These methods allow multiple comparisons at once, either across all combinations or pairwise:
-
batchTest ( a: MetricInput, b: MetricInput, opt? ) : BatchResultLike
Performs a full cross-comparison between every element inaand every element inb. Returns an array of result objects, one for each combination. -
batchSorted ( a: MetricInput, b: MetricInput, dir = 'desc', opt? ) : BatchResultLike
LikebatchTest, but the results are sorted by similarity score in descending or ascending order (dircan bedescorasc). -
pairs ( a: MetricInput, b: MetricInput, opt? ) : BatchResultLike
Compares elements at matching indices in both input arrays. Both inputs must be arrays of equal length. -
match ( a: MetricInput, b: MetricInput, threshold: number, opt? ) : BatchResultLike
Returns only results with a similarity score greater than or equal tothreshold. Results are returned in descending order. -
closest ( a: MetricInput, b: MetricInput, n = 1, opt? ) : BatchResultLike
Returns thenmost similar pairs. -
furthest ( a: MetricInput, b: MetricInput, n = 1, opt? ) : BatchResultLike
Returns thenleast similar pairs.
-
matrix ( input: string[], opt? ) : number[][]
Computes a similarity matrix for all combinations of elements in the input array. Each value represents the similarity score between a pair of strings. The result is a 2D matrix of shape[n][n], wherenis the number of inputs.
In addition to its comparison capabilities, the CmpStr library provides specialized text utilities that support phonetic analysis and normalized string searches:
-
phoneticIndex ( input: string, algo?: string, opt?: PhoneticOptions ) : string
Computes the phonetic representation (or “index”) of the given input string using either a specified algorithm (such as Soundex, Metaphone, Cologne, etc.) or the default algorithm configured on the instance. Instead of a single phonetic index, an array covering all tokens is returned. Optional parameters allow further customization. -
search ( needle: string, haystack: string[], flags?: NormalizeFlags, processors?: CmpStrProcessors ) : string[]
Performs a filtered and normalized substring search across thehaystackarray. Each entry is processed and normalized using the provided flags and processors. Returns all elements that match the normalizedneedle. This method is lightweight and does not compute similarity scores — ideal for fast, rule-based searches.
Introduced in version 3.1, the CmpStr API includes several methods for processing structured data, i.e., they handle input with arrays of objects that are to be compared using a specific key. These methods include:
-
structuredLookup ( query: string, data: T[], key: keyof T, opt?: StructuredDataOptions ) : StructuredResultLike
Performs a batch comparison against structured data by extracting a specific property and returning results with original objects attached. -
structuredMatch ( query: string, data: T[], key: keyof T, threshold: number, opt?: StructuredDataOptions ) : StructuredResultLike
Performs a batch comparison and returns only results above the threshold for structured data. -
structuredClosest ( query: string, data: T[], key: keyof T, n: number = 1, opt?: StructuredDataOptions ) : StructuredResultLike
Returns thenclosest matches from a batch comparison of structured data. -
structuredFurthest ( query: string, data: T[], key: keyof T, n: number = 1, opt?: StructuredDataOptions ) : StructuredResultLike
Returns thenfurthest matches from a batch comparison of structured data. -
structuredPairs ( data: T[], key: keyof T, other: O[], otherKey: keyof O, opt?: StructuredDataOptions ) : StructuredResultLike
Performs a pairwise comparison between two (different) arrays of structured objects by extracting specific properties and returning results with original objects attached.
The CmpStr class also exposes a set of static utilities that provide advanced functionality, including text inspection and diffing, registry access, and cache management. These tools are decoupled from instance-level configuration.
-
CmpStr.analyze ( input: string ) : TextAnalyzer
Returns aTextAnalyzerinstance that can provide structural information about the input string — such as token counts, character groups, numeric patterns, or potential normalization suggestions. -
CmpStr.diff ( a: string, b: string, opt?: DiffOptions ) : DiffChecker
Returns aDiffCheckerinstance for creating unified text diffs between two strings. This tool allows for visual or programmatic inspection of changes, similarities, or transformation paths, and supports custom diff algorithms through options. -
CmpStr.filter
Static interface for global normalization filter management (has,add,remove,pause,resume,list,clear). Filters can be used to dynamically extend or modify the normalization pipeline. -
CmpStr.metric
Static interface to the global metric registry. Provides the ability to register new metrics (add), remove existing ones (remove), check if a metric exists (has) and list all registered metric identifiers (list). This mechanism makes the system extensible with custom similarity scoring algorithms. -
CmpStr.phonetic
Static access to phonetic registry and mapping management. Access to register new phonetic algorithms, retrieve available options, and modify algorithm behavior globally. -
CmpStr.profiler
Provides static access to global profiling and benchmarking services. Useful for analyzing the performance of normalization, comparison, or processing steps across large datasets. -
CmpStr.clearCache
Clears internal caches used by the normalizer, metric system, and phonetic processor modules. This is useful for development, debugging, or dynamic updates in long-running processes.
The CmpStr API is designed with flexibility in mind, offering consistent and predictable input and output types across all core and utility methods. This allows developers to work with both individual strings and string collections, and to adapt result processing to the level of detail required.
-
MetricInput
Mostly all comparison methods accept either a single string or an array of strings (string[]) as input. This applies to both theaandbparameters. Internally, these are normalized to consistent array formats, allowing batch comparisons, one-to-many checks, or full matrix evaluations. -
CmpStrOptions
Many methods optionally accept a configuration object that overrides instance-level settings for a specific call. This object can include a custom metric, normalization flags, processor settings, phonetic parameters, and more. It provides fine-grained control over each operation without affecting the global configuration.
-
ResultLike
Type represents the possible return types for comparison functions. It's a union ofCmpStrResultandMetricResultSingle. -
BatchResultLike
Type represents the possible return types for batch comparison functions. Union type ofCmpStrResult[]andMetricResultBatch. -
StructuredResultLike
Type represents the possible return types for structured data lookups.
-
CmpStrResult
This is the default structured result returned by most comparison methods. It includes:{ source: string; target: string; match: number; }. It is ideal for practical matching and user-facing feedback, balancing clarity with performance. -
MetricResultSingle
Returned whenrawmode is enabled. This represents the internal result object returned by the underlying metric implementation and may include additional metadata, distance scores, or alignment information depending on the metric. -
MetricResultBatch
A batch-level result, consisting of an array ofMetricResultSingleobjects. Used when working withrawmetric output in multi-string comparisons. -
StructuredDataBatchResult
This type describes an array of lookup results, combining aCmpStrResultobject with the original object attached.
Here you will find a simple usage example that showcases some of the methods:
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 ] ]- All methods are chainable where applicable.
- Options can be set globally on the instance or per call.
- By default, all results are formatted as
{ source, target, match }. Setraw: truein options to receive raw metric results. - For asynchronous processing, use
CmpStrAsync.
Refer to the remaining Wiki sections for details on metrics, phonetic algorithms, normalization, and advanced extension points.
CmpStr 3.2 / API Reference • FAQ • npm Package • jsDelivr • DevDocs
CmpStr is a lightweight, fast and well performing package for calculating string similarity.
Getting Started
Installation & Setup
Quick Start
API Reference
Documentation
Similarity Metrics
Phonetic Algorithms
Normalization & Filtering
Comparison Modes
Structured Data
Asynchronous API
Diff & Text Analysis
Extending CmpStr
Project Management