Comparing version 0.0.1 to 0.1.0
{ | ||
"name": "cond-flow", | ||
"version": "0.0.1", | ||
"version": "0.1.0", | ||
"description": "Elixir style cond for easy javascript control flow", | ||
@@ -5,0 +5,0 @@ "main": "src/index.js", |
# cond-flow | ||
Inspired bei Elixir's `cond` (see [case-cond-and-if](https://elixir-lang.org/getting-started/case-cond-and-if.html#cond)) this is a simpler alternative to `_.cond` from [lodash](https://lodash.com/docs/4.17.15#cond) | ||
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/erikmueller/cond-flow.svg?style=shield)](LINK) | ||
[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier) | ||
@@ -23,2 +24,11 @@ [![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com) | ||
## API | ||
```ts | ||
type Cond = ( | ||
pairs: Array<[boolean, unknown | (() => unknown)]>, | ||
options: { strict: boolean } | ||
) => unknown | ||
``` | ||
## Usage | ||
@@ -55,4 +65,24 @@ | ||
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-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. |
@@ -10,5 +10,7 @@ const defaults = { | ||
return match ? match[1] : null | ||
if (!match) return null | ||
return typeof match[1] === 'function' ? match[1]() : match[1] | ||
} | ||
module.exports = cond |
@@ -36,1 +36,14 @@ const cond = require('./index') | ||
}) | ||
test('Accepts functions as value for lazy evaluation', () => { | ||
const falseSpy = jest.fn(() => 'false').mockName('falseHandler') | ||
const trueSpy = jest.fn(() => 'true').mockName('trueHandler') | ||
const value = cond([ | ||
[false, falseSpy], | ||
[true, trueSpy] | ||
]) | ||
expect(falseSpy).not.toHaveBeenCalled() | ||
expect(value).toBe('true') | ||
}) |
178871
8
50
87