1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
// naive pattern matching
const match = (value, ...patterns) => {
for (let [pattern, action] of patterns) {
if (pattern === value || (typeof pattern === 'function' && pattern(value))) {
return action(value);
}
}
throw new Error("No match found");
}
const isNumber = x => typeof x === 'number';
const isString = x => typeof x === 'string';
const result = match(
42,
[1, () => "one"],
[2, () => "two"],
[isNumber, x => `number: ${x}`],
[isString, x => `string: ${x}`]
);
console.log(result);
// slightly fancier pattern matching
const matchObject = (value, ...patterns) => {
for (let [pattern, action] of patterns) {
if (typeof pattern === 'function' && pattern(value)) {
return action(value);
} else if (typeof pattern === 'object' && pattern !== null) {
let isMatch = true;
for (let key in pattern) {
if (pattern[key] !== value[key]) {
isMatch = false;
break;
}
}
if (isMatch) return action(value);
} else if (pattern === value) {
return action(value);
}
}
throw new Error("No match found");
}
const isAdult = person => person.age >= 18;
const isChild = person => person.age < 18;
const personResult = matchObject(
{ name: 'Rachel', age: 30 },
[{ name: 'Rachel', age: 30 }, () => "Rachel, 30 years old"],
[isAdult, person => `${person.name} is an adult`],
[isChild, person => `${person.name} is a child`]
);
console.log(personResult);
// Basic Matching: Checking if a value directly matches a pattern.
// Function Patterns: Uses functions to define more complex matching logic.
// Object Patterns: Match objects based on their properties.
|