Pattern matching without a transpiler.
match(value)(pattern1, pattern2, ...etc) func(pattern1, pattern2, ...etc)(value)
View the Project on GitHub mrkev/fnMatch
Hosted on GitHub Pages — Theme by orderedlist
match("hello")( (_ = "hey") => {}, // doesn't match (_ = "world") => {}, // doesn't match (_ = "hello") => {}, // matches! )
// Prints "undefined" match()( () => console.log('undefined'), (_) => console.log('anything'), ); // Prints "anything" match(3)( () => console.log('undefined'), (_) => console.log('anything'), );
// This prints nothing match([])( ([x, ...y]) => console.log(x, y) )
const contacts = [ {name: {first: "Ajay"}, last: "Gandhi"}, {name: {first: "Seunghee", last: "Han"}}, {name: "Evil Galactic Empire, Inc.", kind: "company"} ] match(contacts)( ([{kind = "company", name}, ..._]) => console.log("Found company:", name) )
const contacts = [ {name: {first: "Ajay"}, last: "Gandhi"}, {name: {first: "Seunghee", last: "Han"}}, {name: "Evil Galactic Empire, Inc.", kind: "company"} ] match(contacts)( ([{name: {first:first_person}}, ..._]) => console.log("First contact is", first_person) )
// Prints "matches" match({name: "Ajay", age: 22})( ({name}) => console.log("matches"), ({name, age}) => console.log("too late!") )
const a = match(3)( (_ = 3) => 4, (_) => 0, ); console.log(a) // Prints 4
const value = { name: 'Ajay', value: { x: 34, }, }; function destructNotes ({notes}) { return notes; } let destructErrors = ({ errors }) => errors; let destructResult = function ({result}) { return result; } let getResult = func( destructNotes, destructErrors, destructResult ); console.log(getResult({notes: "This works!"}))