§ Quick Take
import { strict as assert } from "assert";
import looseCompare from "ast-loose-compare";
assert.equal(
looseCompare(
{
a: {
b: "d",
c: [],
e: "f",
g: "h",
},
},
{
a: {
b: "d",
c: [],
},
}
),
true
);
§ Examples
§ Purpose
To find out, does an object/array/string/nested-mix is a subset or equal to another input.
If this library will encounter two things that contain only empty things, it will report them as equal. Empty things are:
- strings that
trim()
to zero length - arrays with zero or more empty strings (see previous item)
- plain objects whose all values of all keys are empty arrays, empty strings or empty plain objects
For example these two are deemed to be equal:
looseCompare(
{
a: "a",
b: "\n \n\n",
},
{
a: "a",
b: "\t\t \t",
}
);
// => true
Second input argument can be subset of first-one, notice b
values are of a different type, yet both contain only empty space:
looseCompare(
{
a: "a",
b: [[["\n \n\n"]]],
c: "c",
},
{
a: "a",
b: { c: { d: " \t\t \t" } },
}
);
// => true
§ API
looseCompare(bigObj, smallObj)
In other words, it's a function which takes two input arguments, both obligatory.
It returns a boolean or undefined
.
- If everything from
smallObj
matches everything withinbigObj
, this library returnstrue
. - Otherwise, if there's a mismatch, returns
false
. - For all other cases where inputs are missing/
undefined
, returnsundefined
. - If both
smallObj
andbigObj
contain the same key and their values contain only empty space (differing or not), they will be considered equal.
§ Difference from ast-compare
ast-compare of ours does everything that this program does and more.
§ Differences from _.isMatch
"Partial comparisons will match empty array and empty object source values against any array or object value, respectively." — Lodash documentation
_.isMatch positively matches empty arrays to everything. This is bad when you are comparing parsed HTML/CSS trees. This library doesn't do this. In this library, empty array will not be reported as equal to non-empty array, although if both arguments contain something which is empty space, they will be considered equal.
If you want an AST comparison library with a stricter ways towards the empty space equation, check ast-compare.
§ Changelog
See it in the monorepo , on Sourcehut.
§ Licence
Copyright © 2010–2020 Roy Revelt and other contributors
Related packages:
t.same
assert on array of objects, where element order doesn't matter