A functional approach to switches
npm install @omgimalexis/switch-case
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.
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!
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
}
npm run test
👤 Alexis Tyler xo@wvvw.me (https://wvvw.me/)
- Website: https://wvvw.me
- Twitter: @OmgImAlexis
- Github: @OmgImAlexis
Contributions, issues and feature requests are welcome!
Feel free to check issues page.
Give a ⭐️ if this project helped you!