0.0.3 • Published 5 years ago
xwitch v0.0.3
xwitch
xwitch
replaces switch
statement with function call.
xwitch
is short for expression switch
.
Installation
yarn add xwitch
or
npm install xwitch
Usage
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.
switch
is not expression but statement. So, Sometimes, You must declare variable aslet
even if the variable will never changed.case
statement does not create a block scope. that specification makes it difficult to name a variable used in statements associated with thatcase
.- if you forget
break
statement, that causes unexpected behaviors.