0.0.3 • Published 6 years ago
xwitch v0.0.3
xwitch
xwitch replaces switch statement with function call.
xwitch is short for expression switch.
Installation
yarn add xwitchor
npm install xwitchUsage
import xwitch from 'xwitch';
import {AdminIcon, UserIcon, AnonymousIcon} from './some-icon-path';
type UserType = 'admin' | 'normal' | 'anonymous';
const user: UserType = 'admin';
// icon is inferred as ReactElement | null
const icon = xwitch(user)
.case('admin', () => <AdminIcon />)
.case('normal', () => <UserIcon />)
.case('anonymous', () => <AnonymousIcon />)
.default(() => null);API
TODO
Motivation
switch syntax in JavaScript has following disadvantage.
switchis not expression but statement. So, Sometimes, You must declare variable asleteven if the variable will never changed.casestatement does not create a block scope. that specification makes it difficult to name a variable used in statements associated with thatcase.- if you forget
breakstatement, that causes unexpected behaviors.