Skip to Content
  • Website
Codsen
  • Home
  • Open Source
  • Articles
  • About

prevOpen Source→ast-comparenext

ast-compare4.2.5

Compare anything: AST, objects, arrays, strings and nested thereof

Downloads per monthChangelogMIT Licenselibera manifesto
  • the top
  • Installation
  • Quick Take
  • Examples
  • PURPOSE
  • COMPARE()
  • ARRAY MATCHI…
  • WHITESPACE…
  • WILDCARD MAT…
  • PROGRESS AND…
  • DEFAULTS
  • VERSION
  • TYPES
  • OPTS — VERBOSEWHEN…
  • DIFFERENCES…
  • Changelog

No 3rd party dependencies. All dependencies and devDependencies, checked recursively, are Codsen packages.

Permalink to InstallationInstallation

Permalink to Quick TakeQuick Take

Permalink to ExamplesExamples

  • Compare Arrays
  • Compare Plain Objects
  • Compare Strings
  • opts.arrayOrder
  • opts.hungryForWhitespace
  • opts.matchStrictly
  • opts.useWildcards
  • opts.verboseWhenMismatches
  • Report deterministic work and elapsed time
  • Report comparison progress
  • Match each unordered array element only once
  • Compare nested arrays without regard to order
  • Match object keys using wildcards

Purpose

It checks whether one nested value is equal to, or a subset of, another. It is especially useful for comparing abstract syntax trees (ASTs).

We use it to compare parsed HTML and CSS trees or individual branches. It recursively traverses objects and arrays, and it powers ast-delete-object.

The default subset mode is similar to node-tap’s t.match. Set opts.matchStrictly to true when both structures must contain the same number of entries.

compare()

The main function compare() is imported like this:

The function takes two values and an optional options object:

Input argumentTypeRequiredDescription
firstValue
Type: ComparableValue
firstValueComparableValueyesThe value that may contain the requested pattern.
secondPattern
Type: ComparableValue
secondPatternComparableValueyesThe value that must equal, or be a subset of, the first value.
opts
Type: Partial<Opts> or null
optsPartial<Opts> or nullnoOptions. null has the same effect as omitting this argument.
  • A match returns true.
  • A mismatch returns false by default. With verboseWhenMismatches: true, it returns a string that describes the mismatch and its path.
  • Missing arguments and invalid options throw a TypeError or RangeError with a stable throw identifier.

The function does not mutate either input.

The options object has the following shape:

KeyTypeDefaultDescription
arrayOrder
Type: "ordered" or "any"
Default: "ordered"
arrayOrder"ordered" or "any""ordered"Match array patterns as an ordered subsequence, or match each pattern item at any unused position.
hungryForWhitespace
Type: boolean
Default: false
hungryForWhitespacebooleanfalseTreat recursively whitespace-only strings and containers as equivalent empty values.
matchStrictly
Type: boolean
Default: false
matchStrictlybooleanfalseRequire arrays and objects to contain the same number of entries as their patterns.
reportCompletionFunc
Type: function or null
Default: null
reportCompletionFuncfunction or nullnullReceive completion statistics after a comparison.
reportProgressFunc
Type: function or null
Default: null
reportProgressFuncfunction or nullnullReceive monotonic progress percentages.
reportProgressFuncFrom
Type: number
Default: 0
reportProgressFuncFromnumber0Set the start of the progress range.
reportProgressFuncTo
Type: number
Default: 100
reportProgressFuncTonumber100Set the end of the progress range.
verboseWhenMismatches
Type: boolean
Default: false
verboseWhenMismatchesbooleanfalseReturn an explanatory string instead of false when values do not match.
useWildcards
Type: boolean
Default: false
useWildcardsbooleanfalseEnable wildcard string patterns in values and object keys.

The exported defaults object is a frozen, read-only snapshot. Attempting to modify it cannot change later comparisons.

Array matching

With the default arrayOrder: "ordered", pattern items must appear in the first array in the same order, but other items can occur between them. With arrayOrder: "any", every pattern item must match a different item in the first array; repeated or ambiguous items are matched one-to-one.

matchStrictly: true additionally requires equal array lengths and equal object key counts. Wildcard keys and values keep their normal meaning in strict mode.

Whitespace matching

With hungryForWhitespace: true, any two recursively empty values match, even when their container shapes differ. Empty values are:

  • strings containing only whitespace;
  • arrays whose entries are all empty; and
  • plain objects whose values are all empty.

Numbers, booleans, null, undefined, and sparse array holes are meaningful; they are not whitespace. A whitespace-only pattern does not match meaningful content merely because it appears inside an array or object.

Wildcard matching

With useWildcards: true, * matches zero or more characters, including line breaks. Escape it as \* to match a literal asterisk. A leading ! negates the whole pattern. Matching is case-sensitive and anchored to the complete string.

Wildcard object keys are fallbacks: an exact own key takes precedence when it exists. Each wildcard key must consume a different key in the first object, and the corresponding values must recursively match as well.

Progress and completion reports

reportProgressFunc receives the configured start value, monotonic intermediate percentages, and the configured end value. Use reportProgressFuncFrom and reportProgressFuncTo to compose this work into a wider progress range.

reportCompletionFunc receives these statistics:

KeyDescription
candidateComparisons
candidateComparisonsCandidate pairs checked during unordered array or wildcard matching.
comparisons
comparisonsNested value comparisons performed.
matchingEdges
matchingEdgesCompatible candidate pairs found for injective matching.
timeTakenInMilliseconds
timeTakenInMillisecondsBest-effort elapsed time.

Exceptions thrown by either reporting callback are ignored and do not change the comparison result.

defaults

You can import defaults:

It's a plain object:

The main function calculates the options to be used by merging the options you passed with these defaults.

version

You can import version:

Types

This package is written in TypeScript and exports the following types:

TypeDescription
AnyObject
Type: AnyObject
AnyObjectA read-only object with string keys and unknown values.
BooleanOpts
Type: BooleanOpts
BooleanOptsOptions that make compare() return a boolean.
ComparableValue
Type: ComparableValue
ComparableValueA JsonValue or explicit undefined.
CompletionStats
Type: CompletionStats
CompletionStatsCounters and elapsed time passed to reportCompletionFunc.
JsonArray
Type: JsonArray
JsonArrayA read-only array of JsonValue or undefined entries.
JsonObject
Type: JsonObject
JsonObjectA read-only object whose values are JsonValue or undefined.
JsonValue
Type: JsonValue
JsonValueA nested string, number, boolean, null, JsonObject, or JsonArray.
Opts
Type: Opts
OptsThe complete options object documented above.
VerboseOpts
Type: VerboseOpts
VerboseOptsOptions with verboseWhenMismatches: true, making the return type `true
import type {
  AnyObject,
  BooleanOpts,
  ComparableValue,
  CompletionStats,
  JsonArray,
  JsonObject,
  JsonValue,
  Opts,
  VerboseOpts,
} from "ast-compare";

opts.verboseWhenMismatches

Use verboseWhenMismatches: true when you need to explain why a pattern did not match. Every mismatch returns a string containing the failing path, the reason, and correctly labelled first and second values. A successful comparison still returns true.

The VerboseOpts overload exposes this as true | string; it does not return false.

Differences from _.isMatch

Partial comparisons will match empty array and empty object source values against any array or object value, respectively.

Lodash isMatch documentationopens in a new tab

_.isMatchopens in a new tab matches an empty array pattern to every array. That is often undesirable when comparing parsed HTML or CSS trees. This library does not match an empty array pattern to a non-empty array unless hungryForWhitespace is enabled and both values are recursively whitespace-empty.

const result = compare(["a", "b", "c"], []);
// result === false

Permalink to changelogChangelog

Open Changelog
↑ back to top
prev next

Copyright

All rights reserved © Roy Revelt 2026
All our open source packages are under MIT licenceopens in a new tab

Activities

🐛 See a bug? Raise an issueopens in a new tab
💘 Check out the Indiewebopens in a new tab and Libera manifestoopens in a new tab