-
-
Notifications
You must be signed in to change notification settings - Fork 0
match()
Eugene Lazutkin edited this page Jan 11, 2022
·
4 revisions
This function compares a JavaScript object to satisfy a certain structural pattern. It can handle objects with circular dependencies.
isShape() is an alias of this function.
import {match, any} from 'deep6';
match({a: 1, b: 2}, {a: 1}); // true
match({a: 1, b: 2}, {b: 2}); // true
match({a: 1, b: 2}, {c: 3}); // false
match({a: 1, b: 2}, [1, 2]); // false
match({a: 1, b: 2}, {a: any}); // true
match({a: 1, b: 2}, {b: any}); // true
match({a: 1, b: 2}, {c: any}); // false
match({a: 1, b: 2}, any); // true
any is used to match any possible value.
Arguments:
-
object
— a required argument. It can be anything. -
pattern
— a required argument. It can be anything, usually, an object, which lists desired properties, which should be present. -
options
— an optional object. The following optional properties are recognized:-
openObjects
— a boolean flag. Whentrue
all objects inpattern
are treated as incomplete, which causes to ignore the corresponding extra properties inobject
. Otherwise, all objects should match exactly. -
openMaps
— a boolean flag. Whentrue
all maps inpattern
are treated as incomplete, which causes to ignore the corresponding extra properties inobject
. Otherwise, all maps should match exactly. -
openSets
— a boolean flag. Whentrue
all sets inpattern
are treated as incomplete, which causes to ignore the corresponding extra properties inobject
. Otherwise, all sets should match exactly. -
circular
— a boolean flag. Whentrue
, special algorithms are used to detect internal loops in objects.- It is totally safe to turn it on for all objects, but checks will require more memory and more CPU. In some cases, for performance reasons, you may want to turn it off.
-
symbols
— a boolean flag. Whentrue
, symbol properties would be checked for equivalency as well.- Normally symbol properties are hidden from enumerating using classical means.
-
ignoreFunctions
— a boolean flag. Whentrue
, if both properties are functions, they are assumed to be equivalent automatically. -
loose
— a boolean flag. Whentrue
, primitives are compared with==
rather than===
. - Any other properties documented in Traverse: preprocess().
The default:
{openObjects: true, openMaps: true, openSets: true, circular: true}
. -
The function returns a boolean value, which indicates that the first argument matches the second.
Implemented using unify() and Traverse: preprocess():
const defaultMatchOptions = {openObjects: true, openMaps: true, openSets: true, circular: true};
const match = (object, pattern, options = defaultMatchOptions) =>
!!unify(object, preprocess(pattern, options), null, {
circular: options.circular,
symbols: options.symbols,
loose: options.loose,
ignoreFunctions: options.ignoreFunctions
});