Skip to content
Elixir style cond for easy javascript control flow
JavaScript
Branch: master
Clone or download

Latest commit

Latest commit 3bbea4a Mar 23, 2020

Files

Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.circleci Add codecov w/ coverage Mar 23, 2020
src Allow lazy evaluation Mar 21, 2020
.eslintrc Initial commit Mar 20, 2020
.gitignore Add codecov w/ coverage Mar 23, 2020
.npmignore Initial commit Mar 20, 2020
.prettierrc Initial commit Mar 20, 2020
README.md Add codecov badge Mar 23, 2020
package.json Add codecov w/ coverage Mar 23, 2020
yarn.lock Add codecov w/ coverage Mar 23, 2020

README.md

cond-flow

Inspired by Elixir's cond this is a simpler alternative to lodash's _.cond

CI status code style: prettier JavaScript Style Guide tested with jest codecov

Install

Install with npm or yarn via

yarn add cond-flow

or

npm i cond-flow

API

type Cond = (
  pairs: Array<[boolean, unknown | (() => unknown)]>,
  options: { strict: boolean }
) => unknown

Usage

import cond from 'cond-flow'

const value = cond([
  [false, 'false'],
  [true, 'true'],
  [true, 'true but too late']
])

// value === 'true'

You can disable strict checking by passing options as the second argument:

import cond from 'cond-flow'

const value = cond(
  [
    [false, 'false'],
    [1, 'truthy'],
    [true, 'true but also too late']
  ],
  { strict: false }
)

// value === 'truthy'

Also works nicely with React components as you can have the values lazily evaluated by wrapping it in a function:

import cond from 'cond-flow'

const Component = ({ isDisabled, isNew, isLoading }) => (
  <>
    {cond([
      [isLoading, () => <Loading />],
      [isNew, () => <Create />],
      [isDisabled, null]
    ])}
  </>
)

Note

As all predicates have to be evaluated before the right branch can be chosen, it can have a negative performance impact if you rely on heavy computations here. It's best have simple booleans and resort to _.cond for complex use cases.

Development

If you find this useful or would like to add features, feel free to clone the repository and open a PR.

You can’t perform that action at this time.