Class Matcher<T, U>

An abstraction to help you create a simple pattern matching API

interface Member extends Matchable<string> {
name: string;
}

const members: Member[] = [
{ matches: (p) => p.endsWith('.ts'), name: 'typescript' },
{ matches: (p) => p.endsWith('.js'), name: 'javascript' },
];

const matcher = new Matcher(members);

matcher.select('test.js')?.name; // javascript

Type Parameters

Constructors

Properties

Methods

Constructors

Properties

members: T[]

Methods

  • Calls .select() to try and find a match for any of the members. If it can it calls matches otherwise it call noMatch

    Type Parameters

    • W

    Parameters

    • pattern: U
    • matches: (v: T) => W

      Called with the matching member if one exists

    • noMatch: () => W

      Called when no match was found

    Returns W

    matcher.match(
    'name',
    (member) => member.doSomething(),
    () => throw Error('Couldn't do anything!')
    )
  • Iterate over the members and return the first member that matches s.

    Parameters

    • pattern: U

    Returns null | T

    const member = matcher.select('name');

    member.doSomething();
  • Calls .match() to try and find a match if there is no match it returns the provided default value.

    Parameters

    • pattern: U
    • defaultValue: T

      The value returned when the pattern provided doesn't match any member.

    Returns T

    const member = matcher.select('', { matches: () => true, name: 'default' });