@emmafuller/js-match
v0.1.12
Published
Simple matching library for javascript
Downloads
3
Readme
js-match
Note: this library is still experimental. Implementation details are subject to change. For more detailed usage, check the test cases linked on GitLab.
Matching against functions
import match from '@emmafuller/match-js';
const isEven = match(
[x => x % 2 === 0, true],
[x => x % 2 === 1, false]
);
assert.equal(isEven(7), false);
Returning transformed values
import match, { orElse } from '@emmafuller/match-js';
const greet = match(
["Emma", "Hey Emma!! Great to see you, how're the cats?"],
[orElse, name => `Hey, ${name}! I'm not sure we've met`]
);
assert.equal(greet("Jeremy"), "Hey, Jeremy! I'm not sure we've met");
Matching against class type
import match, { isA, orElse } from '@emmafuller/match-js';
class Dog { constructor(name) { this.name = name; } }
const isAGoodBoy = match(
[isA(Dog), "Absolutely"],
[orElse, "Maybe"]
);
const fido = new Dog("Fido");
assert.equal(isAGoodBoy(fido), "Absolutely");
Matching multiple values in a branch
import match, { anyOf, orElse } from '@emmafuller/match-js';
const isEmmasCat = match(
[anyOf(["Diddle", "Ollie"]), true],
[orElse, false]
);
assert.equal(isEmmasCat("Ollie"), true);
assert.equal(isEmmasCat("Chowder"), false);
Using recursion
import match, { anyOf, id, orElse } from '@emmafuller/match-js';
const fibb = match(
[anyOf([0, 1]), id],
[orElse, x => fibb(x - 1) + fibb(x - 2)]
);
assert.equal(fibb(10), 55);