UP | HOME

pattern matching

Table of Contents

1 In Javascript

const isFunction = f =>
  !!(f && f.constructor && f.call && f.apply);

const toPairs = (arr) =>
  arr.reduce(
    (result, value, index, array) => {
      if (index % 2 === 0)
        result.push(array.slice(index, index + 2));
      return result;
    }, []);

const match =
  (...pairs) =>
    (val) =>
      toPairs(pairs)
        .map(
          ([pred, res]) => (
            (isFunction(pred) ? pred(val) : pred)
              ? (isFunction(res) ? res(val) : res)
              : undefined
          )
        )
        .find((v) => !!v)

const f = match(
  v => !!v.isSomething, v => `${v} is something`,
  v => !!v.someValue,   v => "something else",
  true,            "default"
)

console.log(f("hey"))
console.log(  f({ isSomething: true }) )
default
[object Object] is something

Author: John Doe

Created: 2021-04-25 Sun 15:56