Last active
March 18, 2020 02:26
-
-
Save hanh090/69d427eb9b706b5ed0acdd2e20d352e4 to your computer and use it in GitHub Desktop.
Correct way to using memoize in EH project
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Import memoize from lodash fp package - it is convention in EH project | |
import memoize from 'lodash/fp/memoize'; | |
// in lodash functional programming, memoize only have 1 argument | |
// this is code to changed to original API which support keyResolver | |
const memoizeWithResolver = memoize.convert({ fixed: false }); | |
const keyResolver = (...args) => JSON.stringify(args);// Just sample code, you can choose method which you prefer | |
const withMemo = memoizeWithResolver((a,b) => doSomethingWith(a,b), keyResolver) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Import memoize from normal lodash package | |
import memoize from 'lodash/memoize'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import memoize from 'lodash/fp/memoize'; | |
const withMemoize = memoize((a, b) => console.log({ a, b })); | |
withMemoize(3, 5); // Console print: {a:3, b:5} | |
withMemoize(3, 6); // Nothing printed. Reason: cached by first argument | |
const keyResolver = (...args) => { | |
console.log(args); | |
return JSON.stringify(args); | |
}; | |
const withMemoizeAndResolverButWrong = memoize( | |
(a, b) => console.log({ a, b }), | |
keyResolver | |
); | |
withMemoizeAndResolverButWrong(3, 7); // Console print: {a:3, b:7}. keyResolver do not called | |
withMemoizeAndResolverButWrong(3, 8); // Nothing printed. Reason: cached by first argument and key resolver do not called | |
//------------Correct way---------- | |
const memoizeWithResolver = memoize.convert({ fixed: false }); | |
const withMemoizeAndResolver = memoizeWithResolver( | |
(a, b) => console.log({ a, b }), | |
keyResolver | |
); | |
withMemoizeAndResolver(3, 9); // Console print: [3,9], {a:3, b:9}. One from keyresolver, other is memoize | |
withMemoizeAndResolver(3, 10);// Console print: [3,10], {a:3, b:10}. One from keyresolver, other is memoize | |
withMemoizeAndResolver(3, 9); // Nothing printed. Reason: cached |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment