https://github.com/jay-es/nano-match
`nano-match` is a tiny utility simplifying key-based matching in TypeScript, bringing elegance to your code.
https://github.com/jay-es/nano-match
pattern-matching switch-case typescript
Last synced: 5 months ago
JSON representation
`nano-match` is a tiny utility simplifying key-based matching in TypeScript, bringing elegance to your code.
- Host: GitHub
- URL: https://github.com/jay-es/nano-match
- Owner: jay-es
- License: mit
- Created: 2024-01-29T14:26:22.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2024-01-30T14:25:09.000Z (over 2 years ago)
- Last Synced: 2025-10-04T22:32:15.478Z (9 months ago)
- Topics: pattern-matching, switch-case, typescript
- Language: TypeScript
- Homepage: https://www.npmjs.com/package/@jay-es/nano-match
- Size: 24.4 KB
- Stars: 3
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# nano-match 🎯
`nano-match` is a tiny utility simplifying key-based matching in TypeScript, bringing elegance to your code.
## Installation 🚀
```bash
npm install @jay-es/nano-match
```
## Usage ðŸ›
### match ✨
```typescript
import { match } from '@jay-es/nano-match';
type Language = 'en' | 'es' | 'fr';
const lang: Language = 'en';
// Strict matching, only allows valid keys of type 'Language'.
const greeting = match(lang, {
en: "Hello.",
es: "Hola.",
fr: "Bonjour.",
});
console.log(greeting); // Output: Hello. (Type: "Hello." | "Hola." | "Bonjour.")
```
## Type Safety 🛡
- `match` enforces type safety by allowing only valid keys. It ensures that the provided key is of the specified type.
```typescript
// Compilation error: 'de' is not a valid key of type 'Language'.
const strictGreeting = match('de', {
en: "Hello.",
es: "Hola.",
fr: "Bonjour.",
});
```
### Additional Example 🚀
```typescript
// Using `match` with numeric keys
const message = match(200, {
200: "OK",
404: "Not Found",
500: "Internal Server Error",
});
console.log(message); // Output: OK (Type: "OK" | "Not Found" | "Internal Server Error")
```
## Additional Feature 🌟
`nano-match` also provides the following function:
### looseMatch 🎈
As an additional feature, `looseMatch` allows for more flexible matching that accepts keys outside the specified type, returning `undefined` for keys that do not match.
```typescript
import { looseMatch } from '@jay-es/nano-match';
// Loose matching, allows keys outside the specified type, returning undefined for non-matching keys.
const nonMatchingKey: string = 'de';
const looseGreeting = looseMatch(nonMatchingKey, {
en: "Hello.",
es: "Hola.",
fr: "Bonjour.",
});
console.log(looseGreeting); // Output: undefined (Type: "Hello." | "Hola." | "Bonjour." | undefined)
```
## License 📄
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.