-
Notifications
You must be signed in to change notification settings - Fork 85
Closed
Description
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" }"]ppeeouppeeou
Metadata
Metadata
Assignees
Labels
No labels