Skip to content

Commit 0314902

Browse files
authored
Merge pull request #7 from sgrowe/memoisation
Add memoisation of functions
2 parents 39856da + 8104132 commit 0314902

File tree

3 files changed

+14
-3
lines changed

3 files changed

+14
-3
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
> Create an Event handler function that sets a given state property. Works with [preact] and [react].
44
5-
- **Tiny:** less than **300 bytes** of [ES3](https://unpkg.com/linkstate) gzipped
5+
- **Tiny:** less than **350 bytes** of [ES3](https://unpkg.com/linkstate) gzipped
66
- **Familiar:** it's just a function that does what you would have done manually
77
- **Standalone:** one function, no dependencies, works everywhere
88

src/index.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@ import delve from 'dlv';
88
*/
99
export default function linkState(component, key, eventPath) {
1010
let path = key.split('.');
11-
return function(e) {
11+
const cache = component._linkedStates || (component._linkedStates = {});
12+
13+
return cache[`${key}\n${eventPath}`] || (cache[`${key}\n${eventPath}`] = function(e) {
1214
let t = e && e.target || this,
1315
state = {},
1416
obj = state,
@@ -19,5 +21,5 @@ export default function linkState(component, key, eventPath) {
1921
}
2022
obj[path[i]] = v;
2123
component.setState(state);
22-
};
24+
});
2325
}

test/index.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,4 +110,13 @@ describe('linkstate', () => {
110110
expect(component.setState).to.have.been.calledWith({'testStateKey': 'nestedPathValueFromEvent'});
111111
});
112112
});
113+
114+
describe('linkState memoisation', () => {
115+
it('should return the same function when called with the same inputs', () => {
116+
linkFunction = linkState(component, 'nested.state.key');
117+
const linkFunctionB = linkState(component, 'nested.state.key');
118+
119+
expect(linkFunction).to.equal(linkFunctionB);
120+
});
121+
});
113122
});

0 commit comments

Comments
 (0)