Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/mudssrali/cond-construct
Elixir's cond construct implementation for Javascript and Typescript
https://github.com/mudssrali/cond-construct
cond control-flow elixir-cond elixir-lang javascript typescript
Last synced: about 1 month ago
JSON representation
Elixir's cond construct implementation for Javascript and Typescript
- Host: GitHub
- URL: https://github.com/mudssrali/cond-construct
- Owner: mudssrali
- Created: 2020-05-01T23:30:43.000Z (over 4 years ago)
- Default Branch: master
- Last Pushed: 2022-09-28T19:03:09.000Z (about 2 years ago)
- Last Synced: 2024-09-14T16:24:02.136Z (2 months ago)
- Topics: cond, control-flow, elixir-cond, elixir-lang, javascript, typescript
- Language: TypeScript
- Homepage:
- Size: 124 KB
- Stars: 2
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# cond-construct
Inspired by [Elixir's `cond`](https://elixir-lang.org/getting-started/case-cond-and-if.html#cond) this is a simpler alternative to [lodash's `_.cond`](https://lodash.com/docs/4.17.15#cond)
[![CI status](https://circleci.com/gh/mudssrali/cond-construct.svg?style=shield)](LINK)
[![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com)
[![tested with jest](https://img.shields.io/badge/tested_with-jest-99424f.svg)](https://github.com/facebook/jest)
## Install
Install with npm or yarn via
```
yarn add cond-construct
```or
```
npm i cond-construct
```## API
```ts
type Cond = (
pairs: Array<[boolean, unknown | (() => unknown)]>,
options?: { strict: boolean }
) => unknown
```## Usage
```js
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:
```js
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:
```jsx
import cond from 'cond-construct'const Component = ({ hasErrors, isNew, isLoading }) => (
<>
{cond([
[isLoading, () => ],
[isNew, () => ],
[hasErrors, () => ]
])}
>
)
```### Next
- [] Handle multiple method executions
- [] Add more option for falsy value### 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.