matchr
Powerful JavaScript value matching.
Install
const matchr = require('matchr');
Features
Basics
matchr({ a: 1, b: 2 }, { a: 1 });
matchr([1, 2, 3], [1]);
matchr([1, 2, 3], [1, 2]);
matchr([1, 2, 3], [2, 1]);
Date matching
matchr(new Date('2016-08-14T05:00:00.000Z'), new Date('2016-08-14T05:00:00.000Z')));
matchr(new Date('2016-08-14T05:00:00.000Z'), '2016-08-14T05:00:00.000Z'));
matchr(new Date('2016-08-14T05:00:00.000Z'), 1471150800000));
RegExp matching
matchr(/oh/, /oh/);
matchr('John', /oh/);
matchr(42, /4[0-9]/);
matchr(new Date('2017-01-20T18:48:08.745Z'), /2017/);
Function matching
const isNumber = (n) => typeof n === 'number';
matchr(42, isNumber);
Type matching
matchr([], Array);
matchr(true, Boolean);
matchr(false, Boolean);
matchr(() => {}, Function);
matchr({}, Object);
matchr('Hello World!', String);
Deep matching
matchr(
{ person: { name: 'John' } },
{ person: { name: 'John' } }
);
matchr(
[{ a: 1 }, { b: 2 }],
[{ a: 1 }]
);
matchr(
[{ a: 1 }, { b: 2 }],
[{ a: 1 }]
);
Deep matching uses matchr
recursively to match property values.
matchr({
name: 'John',
age: 40,
gender: 'm',
hasBand: true
}, {
name: String,
age: Number,
gender: /f|m/
});
Matching options
matchPartialObjects (default: true
)
matchr(
{ a: 1, b: 2 },
{ a: 1 },
{ matchPartialObjects: true }
);
matchr(
{ a: 1, b: 2 },
{ a: 1 },
{ matchPartialObjects: false }
);
matchPartialArrays (default: true
)
matchr(
[1, 2, 3],
[1, 2],
{ matchPartialArrays: true }
);
matchr(
[1, 2, 3],
[1, 2],
{ matchPartialArrays: false }
);
matchOutOfOrderArrays (default: true
)
matchr(
[1, 2, 3],
[3, 2, 1],
{ matchOutOfOrderArrays: true }
);
matchr(
[1, 2, 3],
[3, 2, 1],
{ matchOutOfOrderArrays: false }
);
Changing default matching options
matchr.setDefaultOptions({
});
FP support
matches
reverses argument order and splits function in two to allow a more functional style.
const matches = require('matchr/matches');
const hasANumber = matches({ a: Number });
hasANumber({ a: 1, b: 2 });
Chai plugin
Plug matchr
into chai.
const chai = require('chai');
const matchr = require('matchr/chai');
chai.use(matchr);
chai.expect({ a: 1, b: 2 }).to.matchr({ a: 1 });
chai.expect({ a: 1, b: 2 }).to.matchr({ a: 1, b: 2 }, { matchPartialObjects: false });
chai.expect({ a: 1, b: 2 }).to.not.matchr({ c: 3 });
Jest plugin
Plug matchr
into jest.
const matches = require('matchr/jest');
expect({ a: 1, b: 2 }).toEqual(matches({ a: 1 }));
expect({ a: 1, b: 2 }).toEqual(matches({ a: 1, b: 2 }, { matchPartialObjects: false }));
expect({ a: 1, b: 2 }).not.toEqual(matches({ c: 3 }));
const func = jest.fn();
func('test');
expect(func).toHaveBeenCalledWith(matches(/es/));
NOTE I'm waiting for facebook/jest/pull/2476 to land in a release to improve the output of the asymmetric matcher.