Skip to content

API Reference

Paul Köhler edited this page Jan 23, 2026 · 15 revisions

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.

Instantiation and Options

Creating an 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.

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.

Working with Options

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 call

Internally, options are deeply merged and accessed via dot-separated paths, allowing flexible and targeted updates of nested configuration fields.

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.

Common Configuration Fields

Some of the most commonly used configuration keys include:

  • metric Specifies the similarity algorithm to use (e.g., levenshtein, jaroWinkler, dice).
  • flags A string controlling normalization behavior (e.g., i for case-insensitive, d to remove numbers).
  • processors Defines additional preprocessing steps, including phonetic mappings.
  • 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.

Metric and Preprocessing Configuration

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.

Core Comparison Methods

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:

  • a Source input — a string or an array of strings.
  • b Target input — a string or an array of strings.
  • opt (optional) A configuration object overriding instance options for this call.

Single Comparison

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. When raw mode 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).

Batch and Pairwise Comparison

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 in a and every element in b. Returns an array of result objects, one for each combination.

  • batchSorted ( a: MetricInput, b: MetricInput, dir = 'desc', opt? ) : BatchResultLike
    Like batchTest, but the results are sorted by similarity score in descending or ascending order (dir can be desc or asc).

  • 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 to threshold. Results are returned in descending order.

  • closest ( a: MetricInput, b: MetricInput, n = 1, opt? ) : BatchResultLike
    Returns the n most similar pairs.

  • furthest ( a: MetricInput, b: MetricInput, n = 1, opt? ) : BatchResultLike
    Returns the n least similar pairs.

Matrix

  • 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], where n is the number of inputs.

Phonetic and Text Utilities

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 the haystack array. Each entry is processed and normalized using the provided flags and processors. Returns all elements that match the normalized needle. This method is lightweight and does not compute similarity scores — ideal for fast, rule-based searches.

Structured Data

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 the n closest matches from a batch comparison of structured data.

  • structuredFurthest ( query: string, data: T[], key: keyof T, n: number = 1, opt?: StructuredDataOptions ) : StructuredResultLike
    Returns the n furthest 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.

Static Utilities

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 a TextAnalyzer instance 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 a DiffChecker instance 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.

Parameters and Return Types

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.

Input Types

  • MetricInput
    Mostly all comparison methods accept either a single string or an array of strings (string[]) as input. This applies to both the a and b parameters. 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.

Return Types

  • ResultLike
    Type represents the possible return types for comparison functions. It's a union of CmpStrResult and MetricResultSingle.

  • BatchResultLike
    Type represents the possible return types for batch comparison functions. Union type of CmpStrResult[] and MetricResultBatch.

  • 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 when raw mode 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 of MetricResultSingle objects. Used when working with raw metric output in multi-string comparisons.

  • StructuredDataBatchResult
    This type describes an array of lookup results, combining a CmpStrResult object with the original object attached.

Example Usage

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 ] ]

Notes

  • 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 }. Set raw: true in 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.

Clone this wiki locally