Conditional logic expressed using natural-language operators via JavaScript template literals.
Why? An experimental project for fun and learning, exploring alternative syntax for conditional logic.
- CodeSandbox (check console output)
- Local examples
- Unit tests
- Integration tests
- Tests with JS eval() as comparator
npm install ifless and use as follows:
import { when } from '@twistezo/ifless'
// or const { when } = require('@twistezo/ifless')
const user = { active: true }
const isAdmin = false
// classic
if (user.active && !isAdmin) {
console.log('condition met')
}
// with 'when'
when`${user.active} AND NOT ${isAdmin}`(() => {
console.log('condition met')
})
// with context and aliases
when.ctx({
admin: isAdmin,
userActive: user.active,
})`#userActive AND NOT #admin`(() => {
console.log('condition met')
})
// complex example
when.ctx({
a: true,
b: false,
c: false,
})`(#a AND #b) OR (NOT #c AND ${true})`(() => {
console.log('condition met')
})Accepted:
${value}#alias- operators
AND,OR,NOT - parentheses
(,)
Not accepted:
- other words
- empty parentheses
- double negations
NOT NOT,!!${value},#{!!value} - aliases without value in context
- functions in context
-
AND,&&- Before:
if (a && b)
- After:
when.ctx({ a, b })`#a AND #b`(() => {})
- Before:
-
OR,||- Before:
if (a || b)
- After:
when.ctx({ a, b })`#a OR #b`(() => {})
- Before:
-
NOT,!- Before:
if (!a)
- After:
when.ctx({ a })`NOT #a`(() => {})
- Before:
-
Parentheses
- Before:
if ((a && b) || (!c && (d || e)))
- After:
when.ctx({ a, b, c, d, e })`(#a AND #b) OR (NOT #c AND (#d OR #e))`(() => {})
- Before:
-
Short-circuit evaluation
- Before:
if (a && expensiveCheck())
- After:
when`${a} AND ${() => expensiveCheck()}`(() => {})
- Before:
-
Double negation
!!- Before:
if (!!a && !!b)
- After:
when.ctx({ a, b })`#a AND #b`(() => {})
- Before:
-
null/undefinedasfalse- Before:
if (a != undefiend && b != null)
- After:
when.ctx({ a, b })`#a AND #b`(() => {})
- Before:
bun run example # run examples
bun run build # build all formats
bun run test # run all tests
bun run lint # check lint
bun run lint:fix # fix lint & format
bun run typecheck # check types
bunx npm login # login to npm
bun publish # publish to npm