| version: 2.1 | ||
| orbs: | ||
| node: circleci/node@1.1.6 | ||
| jobs: | ||
| build-and-test: | ||
| executor: | ||
| name: node/default | ||
| steps: | ||
| - checkout | ||
| - node/with-cache: | ||
| steps: | ||
| - run: yarn | ||
| - run: yarn test | ||
| workflows: | ||
| build-and-test: | ||
| jobs: | ||
| - build-and-test |
+1
-1
| { | ||
| "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", |
+31
-1
| # 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) | ||
| [](LINK) | ||
| [](https://github.com/prettier/prettier) | ||
@@ -23,2 +24,11 @@ [](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. |
+3
-1
@@ -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 |
+13
-0
@@ -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
0.83%8
14.29%50
28.21%87
52.63%