@gabrielrufino/matchjs
v1.1.3
Published
[](https://gabrielrufino.com) [({
a: () => 'Letter A',
b: () => 'Letter B',
[otherwise]: () => 'Other value'
})
console.log(result) // Output: "Letter A"Using include
const result = match('a')({
[include('a', 'b', 'c')]: () => 'In set A, B, or C',
[otherwise]: () => 'Other value'
})
console.log(result) // Output: "In set A, B, or C"Using exclude
const result = match('d')({
[exclude('a', 'b', 'c')]: () => 'Not in A, B, or C',
[otherwise]: () => 'Other value'
})
console.log(result) // Output: "Not in A, B, or C"Using object
const user = { name: 'John', age: 30 }
const result = match(user)({
[object({ name: 'John', age: 30 })]: () => 'Exact user match',
[object({ name: 'Jane' })]: () => 'Different user',
[otherwise]: () => 'Unknown user'
})
console.log(result) // Output: "Exact user match"Complex Object Matching
const data = {
user: { id: 1, profile: { name: 'Alice' } },
settings: { theme: 'dark' }
}
const result = match(data)({
[object({
user: { id: 1, profile: { name: 'Alice' } },
settings: { theme: 'dark' }
})]: () => 'Complex match found',
[otherwise]: () => 'No match'
})
console.log(result) // Output: "Complex match found"🛠️ API
match(value)
Parameters
value: The value to be evaluated (string, number, symbol, or object).
Returns
A function that accepts an options object in the format { key: () => any }, where:
keycan be:- An exact value to match (for primitive values).
- An operator like
include,exclude, orobject. - The
otherwisesymbol as a fallback.
Examples
See the Usage section.
include(...values)
Defines a set of values. Returns true if the value is included in the set.
exclude(...values)
Defines a set of values. Returns true if the value is not included in the set.
object(value)
Defines an object pattern for deep equality matching. Returns true if the input value deeply equals the provided object.
Parameters
value: The object pattern to match against.
Example
const result = match({ a: 1, b: { c: 2 } })({
[object({ a: 1, b: { c: 2 } })]: () => 'Deep match!',
[otherwise]: () => 'No match'
})otherwise
A special symbol used as a fallback for unmatched cases.
🧪 Testing
This project uses Vitest for testing.
To run the tests:
npm test🛡️ Contribution
Contributions are welcome! Please follow these steps:
- Fork the repository.
- Create a new branch for your changes:
git checkout -b my-feature. - Make your changes and commit:
git commit -m "My new feature". - Push to your branch:
git push origin my-feature. - Open a Pull Request.
📄 License
This project is licensed under The Unlicense. See the LICENSE file for details.
