about summary refs log tree commit diff stats
path: root/p9c
Commit message (Collapse)AuthorAgeFilesLines
* *elioat2024-08-252-0/+53
|
* *elioat2024-07-061-3/+2
|
* *elioat2024-07-051-1/+1
|
* *elioat2024-07-051-1/+7
|
* *elioat2024-07-051-0/+80
|
* *elioat2024-01-201-0/+36
|
* *eli-oat2023-05-261-1/+1
|
* *elioat2023-05-261-0/+1
|
* "*"elioat2023-05-261-1/+1
|
* "*"elioat2023-05-262-1/+1
|
* "*"elioat2023-05-262-3/+15
|
* "*"elioat2023-05-251-2/+5
|
* "*"elioat2023-05-251-2/+7
|
* "*"elioat2023-05-251-0/+13
|
* "*"elioat2023-05-254-0/+173
|
* *elioat2023-05-256-0/+0
|
* *elioat2023-05-252-2/+2
|
* *elioat2023-05-254-3/+156
|
* *elioat2023-05-171-0/+0
| | | | '
* *elioat2022-10-191-0/+1214
|
* *elioat2022-10-023-0/+16
class="p">(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.