Skip to content

function: match #346

@2chanhaeng

Description

@2chanhaeng

Suggestion

⭐ Suggestion

It's a some kind of when extension.

match(
  cond1, then1,
  cond2, then2,
  ....,
  // default=identify
)
const match = (...fns: Function[]) => function <T>(x: T){
  for(const [cond, fn] of chunk(2, fns)) {
    if(!fn) return cond(x); // if `fns` has an odd number of item, the last function is default
    if(cond(x)) return fn(x);
  }
  return x // if `fns` has an even number of item, just return arg 
}

The Function[] is not good type, so the real implement should overwrite interface by every case like pipe.

💻 Use Cases

const users = [
  { name: "Kim", gender: "male" },
  { name: "Lee", gender: "female", grade: "doctor" },
  { name: "Park", gender: null },
];

console.log(
  pipe(
    users,
    map(match(
      (user) => user.grade === "doctor", ({ name }) => `Dr. ${name}`,
      (user) => user.gender === "female", ({ name }) => `Ms. ${name}`,
      (user) => user.gender === "male", ({ name }) => `Mr. ${name}`,
      ({ name }) => `Dear ${name}`,
    )),
    toArray,
  ),
); // ["Mr. Kim", "Dr. Lee", "Dear Park"]

const data = [1, "a", { a: "1" }];
console.log(
  pipe(
    data,
    match(
      isNumber, String,
      isObject, JSON.stringify,
    )
    toArray,
  )
); // ["1", "a", "{ a: "1" }"]

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions