fnMatch

Pattern matching without a transpiler.

  1. Usage
  2. Values
  3. Arrays
  4. Objects
  5. Notes

Usage

match(value)(pattern1, pattern2, ...etc)
func(pattern1, pattern2, ...etc)(value)

Learn More

View the Project on GitHub mrkev/fnMatch

Hosted on GitHub Pages — Theme by orderedlist

Values

match("hello")(
  (_ = "hey") => {}, // doesn't match
  (_ = "world") => {}, // doesn't match
  (_ = "hello") => {}, // matches!
)

"Nothing" vs "Anything"


// Prints "undefined"
match()(
  () => console.log('undefined'),
  (_) => console.log('anything'),
);

// Prints "anything"
match(3)(
  () => console.log('undefined'),
  (_) => console.log('anything'),
);

OCaml-like exact semantics

// This prints nothing
match([])(
  ([x, ...y]) => console.log(x, y)
)

Destructuring

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)
)

Renaming

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)
)

Top to bottom

// Prints "matches"
match({name: "Ajay", age: 22})(
  ({name}) => console.log("matches"),
  ({name, age}) => console.log("too late!")
)

It's an expression

const a = match(3)(
  (_ = 3) => 4,
  (_) => 0,
);
console.log(a) // Prints 4

It's Just Functions

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!"}))