Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/omgimalexis/switch-case
A functional approach to switches
https://github.com/omgimalexis/switch-case
Last synced: 29 days ago
JSON representation
A functional approach to switches
- Host: GitHub
- URL: https://github.com/omgimalexis/switch-case
- Owner: OmgImAlexis
- Created: 2019-11-04T02:00:19.000Z (about 5 years ago)
- Default Branch: main
- Last Pushed: 2023-06-12T08:02:42.000Z (over 1 year ago)
- Last Synced: 2024-10-14T07:53:40.986Z (about 1 month ago)
- Language: TypeScript
- Size: 1.14 MB
- Stars: 2
- Watchers: 3
- Forks: 1
- Open Issues: 5
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
Awesome Lists containing this project
README
Welcome to switch-case 👋
> A functional approach to switches
## Install
```sh
npm install @omgimalexis/switch-case
```
## UsageThe latest release now supports both `require` and `import` JavaScript syntax, and provides a more complete TypeScript system. This gives your editor super powers like more exhaustive types and intellisense when used with more advanced features like `as const`. Functional switches will return their real case type; you can use the library synchronously for every non-async case.
```typescript
import { Switch } from '@omgimalexis/switch-case'const { Case } = Switch({
a: 1,
b: 2,
default: async () => 3 as const
} as const)// Returns selected case
const result1 = Case('a');
// ^ const result1: 1console.log(result1)
// Expected: 1// Returns default case when selected isn't found
const result2 = await Case('z');
// ^ const result2: 3console.log(result2)
// Expected: 3
```The version `0.0.3` style of switch case function is still available for migration so your projects just work. It also benefits from the new type system!
```js
const switchCase = require('@omgimalexis/switch-case').default;// Returns selected case
{
const case = 'a';
const result = await switchCase({
a: 1,
b: 2,
default: 3
}, case);// result = 1
}// Returns default case when selected isn't found
{
const case = 'z';
const result = await switchCase({
a: 1,
b: 2,
default: 3
}, case);// result = 3
}// Allows functions
{
const case = 'a';
const result = await switchCase({
a: () => 1,
b: 2,
default: 3
}, case);// result = 1
}// Allows async functions
{
const case = 'a';
const result = await switchCase({
a: async () => 1,
b: 2,
default: 3
}, case);// result = 1
}
```## Run tests
```sh
npm run test
```## Author
👤 **Alexis Tyler (https://wvvw.me/)**
* Website: https://wvvw.me
* Twitter: [@OmgImAlexis](https://twitter.com/OmgImAlexis)
* Github: [@OmgImAlexis](https://github.com/OmgImAlexis)## 🤝 Contributing
Contributions, issues and feature requests are welcome!
Feel free to check [issues page](https://github.com/omgimalexis/switch-case).## Show your support
Give a ⭐️ if this project helped you!