Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

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

Awesome Lists containing this project

README

        

Welcome to switch-case 👋



Version
License: MIT
Twitter: OmgImAlexis

> A functional approach to switches

## Install

```sh
npm install @omgimalexis/switch-case
```

## Usage

The 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: 1

console.log(result1)
// Expected: 1

// Returns default case when selected isn't found
const result2 = await Case('z');
// ^ const result2: 3

console.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!