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.arrayOrderopts.hungryForWhitespaceopts.matchStrictlyopts.useWildcardsopts.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 argument | Type | Required | Description |
|---|---|---|---|
firstValueType: ComparableValue | |||
firstValue | ComparableValue | yes | The value that may contain the requested pattern. |
secondPatternType: ComparableValue | |||
secondPattern | ComparableValue | yes | The value that must equal, or be a subset of, the first value. |
optsType: Partial<Opts> or null | |||
opts | Partial<Opts> or null | no | Options. null has the same effect as omitting this argument. |
- A match returns
true. - A mismatch returns
falseby default. WithverboseWhenMismatches: true, it returns a string that describes the mismatch and its path. - Missing arguments and invalid options throw a
TypeErrororRangeErrorwith a stable throw identifier.
The function does not mutate either input.
The options object has the following shape:
| Key | Type | Default | Description |
|---|---|---|---|
arrayOrderType: "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. |
hungryForWhitespaceType: booleanDefault: false | |||
hungryForWhitespace | boolean | false | Treat recursively whitespace-only strings and containers as equivalent empty values. |
matchStrictlyType: booleanDefault: false | |||
matchStrictly | boolean | false | Require arrays and objects to contain the same number of entries as their patterns. |
reportCompletionFuncType: function or nullDefault: null | |||
reportCompletionFunc | function or null | null | Receive completion statistics after a comparison. |
reportProgressFuncType: function or nullDefault: null | |||
reportProgressFunc | function or null | null | Receive monotonic progress percentages. |
reportProgressFuncFromType: numberDefault: 0 | |||
reportProgressFuncFrom | number | 0 | Set the start of the progress range. |
reportProgressFuncToType: numberDefault: 100 | |||
reportProgressFuncTo | number | 100 | Set the end of the progress range. |
verboseWhenMismatchesType: booleanDefault: false | |||
verboseWhenMismatches | boolean | false | Return an explanatory string instead of false when values do not match. |
useWildcardsType: booleanDefault: false | |||
useWildcards | boolean | false | Enable 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:
| Key | Description |
|---|---|
candidateComparisons | |
candidateComparisons | Candidate pairs checked during unordered array or wildcard matching. |
comparisons | |
comparisons | Nested value comparisons performed. |
matchingEdges | |
matchingEdges | Compatible candidate pairs found for injective matching. |
timeTakenInMilliseconds | |
timeTakenInMilliseconds | Best-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:
| Type | Description |
|---|---|
AnyObjectType: AnyObject | |
AnyObject | A read-only object with string keys and unknown values. |
BooleanOptsType: BooleanOpts | |
BooleanOpts | Options that make compare() return a boolean. |
ComparableValueType: ComparableValue | |
ComparableValue | A JsonValue or explicit undefined. |
CompletionStatsType: CompletionStats | |
CompletionStats | Counters and elapsed time passed to reportCompletionFunc. |
JsonArrayType: JsonArray | |
JsonArray | A read-only array of JsonValue or undefined entries. |
JsonObjectType: JsonObject | |
JsonObject | A read-only object whose values are JsonValue or undefined. |
JsonValueType: JsonValue | |
JsonValue | A nested string, number, boolean, null, JsonObject, or JsonArray. |
OptsType: Opts | |
Opts | The complete options object documented above. |
VerboseOptsType: VerboseOpts | |
VerboseOpts | Options 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.
_.isMatch 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