Pattahn
Readme
Conditions
ConditionIntoConditionCase: ConditionCase: FunctionCase: RegExpCase: Other ObjectCase: Primitivematch (chain)

IntoCondition

Some APIs will convert non-Condition values to a Condition using some simple logic.

Functions that perform this conversion are documented as taking a value of type IntoCondition.

You can explicitly invoke this behavior with Condition.from(value).

import { Condition } from 'pattahn/core';
expect(Condition.from(7).test(7)).toBe(true);

The "Case" sections are in order of preference (if one doesn't match, then the next is tried).

Case: Condition

If the value is a Condition instance, then it's returned immediately and unmodified.

import Eq from 'pattahn/cond/Eq';
const arg = Eq(7);
const condition = Condition.from(arg);
expect(arg).toBe(condition);

Case: Function

The function will be wrapped in Test.

const arg = (x) => x > 10;
const condition = Condition.from(arg);
expect(condition.exec(20)).toEqual([20]);
expect(condition.exec(5)).toBe(null);

Case: RegExp

The regex will be wrapped in RegexTest.

const arg = /^ba.$/;
const condition = Condition.from(arg);
expect(condition.exec('bar')).toEqual(['bar']);
expect(condition.exec('baz')).toEqual(['baz']);
expect(condition.exec('foo')).toBe(null);

Case: Other Object

The object will be used as a MatchObject. This can be nested as MatchObject uses intoCondition on the properties.

const arg = { a: 'foo', b: { c: Eq('bar').or(Eq('baz')) } };
const condition = Condition.from(arg);
const good = {
a: 'foo',
b: {
c: 'baz',
},
};
const bad = {
a: 'foo',
b: {
c: 'quux',
},
};
expect(condition.exec(good)).toEqual([good]);
expect(condition.exec(bad)).toBe(null);

Case: Primitive

The final case is where it's a primitive, and we simply wrap it in Eq.

for (const value of [7, 'foo', null, undefined, true, false]) {
const condition = Condition.from(value);
expect(condition.exec(value)).toEqual([value]);
}