Skip to content

Commit 81a7d07

Browse files
author
Luke Westby
committed
add lazy evaluation
1 parent 33833f4 commit 81a7d07

File tree

3 files changed

+34
-6
lines changed

3 files changed

+34
-6
lines changed

README.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ renderIf(predicate)(element)
1010
## What it looks like
1111

1212
`renderIf` is a curried function that takes a predicate and returns a function accepting an element that will only be returned if the predicate is satisfied.
13+
The function returned by `renderIf` will also accept a parameterless function which will only be invoked if the predicate is satisfied, allowing for lazy evaluation of inner JSX.
1314

1415
```js
1516
renderIf(1 + 1 === 2)(
@@ -31,6 +32,20 @@ class MyComponent extends Component {
3132
}
3233
```
3334

35+
### As a lazy in-line expression
36+
37+
```jsx
38+
class MyComponent extends Component {
39+
render() {
40+
return (
41+
{renderIf(1 + 2 === 3)(() => (
42+
<span>This is only invoked if the universe is working</span>
43+
))}
44+
);
45+
}
46+
}
47+
```
48+
3449
### As a named function
3550

3651
```jsx

renderIf.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
11
'use strict';
22

3-
export default predicate => element => predicate && element;
3+
const isFunction = input => typeof input === 'function';
4+
5+
export default predicate => elemOrThunk =>
6+
predicate ? (isFunction(elemOrThunk) ? elemOrThunk() : elemOrThunk) : null;

test.js

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,23 @@ import {expect} from 'chai';
44
import renderIf from './renderIf';
55

66
describe('renderIf', () => {
7-
it ('should return a function', () => {
7+
it('should return a function', () => {
88
expect(typeof renderIf()).to.be.eql('function');
99
});
10-
it ('should return the element when the predicate passes', () => {
11-
expect(renderIf(true)('foobar')).to.be.eql('foobar');
10+
describe('non-lazy', () => {
11+
it('should return the element when the predicate passes', () => {
12+
expect(renderIf(true)('foobar')).to.be.eql('foobar');
13+
});
14+
it('should not return the element when the predicate fails', () => {
15+
expect(renderIf(false)('foobar')).to.be.eql(null);
16+
});
1217
});
13-
it ('should not return the element when the predicate fails', () => {
14-
expect(renderIf(false)('foobar')).to.be.eql(false);
18+
describe('lazy', () => {
19+
it('should return the result of the thunk when the predicate passes', () => {
20+
expect(renderIf(true)(() => 'foobar')).to.be.eql('foobar');
21+
});
22+
it('should not return the result of the thunk when the predicate fails', () => {
23+
expect(renderIf(false)(() => 'foobar')).to.be.eql(null);
24+
});
1525
});
1626
});

0 commit comments

Comments
 (0)