Skip to content

twistezo/ifless

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

42 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ifless

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.

Examples

Usage

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')
})

Limitations

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

Features

  • AND, &&

    • Before:
      if (a && b)
    • After:
      when.ctx({ a, b })`#a AND #b`(() => {})
  • OR, ||

    • Before:
      if (a || b)
    • After:
      when.ctx({ a, b })`#a OR #b`(() => {})
  • NOT, !

    • Before:
      if (!a)
    • After:
      when.ctx({ a })`NOT #a`(() => {})
  • 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))`(() => {})
  • Short-circuit evaluation

    • Before:
      if (a && expensiveCheck())
    • After:
      when`${a} AND ${() => expensiveCheck()}`(() => {})
  • Double negation !!

    • Before:
      if (!!a && !!b)
    • After:
      when.ctx({ a, b })`#a AND #b`(() => {})
  • null/undefined as false

    • Before:
      if (a != undefiend && b != null)
    • After:
      when.ctx({ a, b })`#a AND #b`(() => {})

Development

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

About

Conditional logic expressed using natural-language operators via JavaScript template literals.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors