Novices Performing Miracles

    cond-construct
    TypeScript icon, indicating that this package has built-in type declarations

    1.0.1 • Public • Published

    cond-construct

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

    CI status JavaScript Style Guide tested with jest

    Install

    Install with npm or yarn via

    yarn add cond-construct
    

    or

    npm i cond-construct
    

    API

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

    Usage

    import cond from 'cond-construct'
     
    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-construct'
     
    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-construct'
     
    const Component = ({ hasErrors, isNew, isLoading }) => (
      <>
        {cond([
          [isLoading, () => <Loading />],
          [isNew, () => <Create />],
          [hasErrors, () => <ShowErrors />]
        ])}
      </>
    )

    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.

    Install

    npm i cond-construct

    DownloadsWeekly Downloads

    3

    Version

    1.0.1

    License

    MIT

    Unpacked Size

    3.44 kB

    Total Files

    4

    Last publish

    Collaborators

    • mudssrali