;const isAllowed =;
const isAllowed =userType === 'employee' ? true : userType === 'customer' ? false : false;
- Ternary expressions are ugly and even more so when nested.
- Solutions like lodash.cond have unnecessary function invocation overhead and are less readable. To ensure lazy evaluation we need to wrap each branch in function.
- We love fluent APIs.
This utility is implemented as a babel-macro.
npm install --save-dev babel-plugin-macros
- Add babel-plugin-macros to .babelrc (if not already preset):
// .babelrcmoduleexports =presets:// ... other presetsplugins:'babel-plugin-macros' // <-- REQUIRED// ... other plugins;
- Branches are evaluated lazily
// src/foo.js;const isAllowed =;// if userType is "employee" then isCustomerAllowed function will never be// executed
Usage with TypeScript
This library is type-safe and comes with type definitions.
All code must be processed through babel. Compilation through tsc (only) is not supported.
Recommended babel configuration:
// .babelrcmoduleexports =presets:'@babel/preset-typescript'// ... other presetsplugins:'babel-plugin-macros'// ... other plugins;
Flow based type inference
One caveat is that TypeScript's flow-based type inference will not treat
.default branches same as normal
AFAIK, currently there is no workaround for feasible.
Every Switch/case/default chain fluent must end with an terminating invocation without interruptions.
const a = 10;const intermediate = ;const result = ;
Above code will fail to compile.
Because the entire Switch/case/end chain is compiled away, anything returned by Switch/case/default can not be assigned, referenced, or used in any computation.
You may also like:
- if-expr.macro: Similar utility, providing a fluent expression-oriented macro replacement for if statement