Last active
December 20, 2018 10:55
-
-
Save ranbena/ace17bb4bb6015f2d22c9f60427e78be to your computer and use it in GitHub Desktop.
Memoized getter decorator
This file contains hidden or 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 { has } from 'lodash-es' | |
// @flow | |
export function memoized( | |
target: any, | |
propertyKey: string, | |
descriptor: PropertyDescriptor<*> | |
) { | |
const originalGet = descriptor.get | |
const memKey = '__memoized__' | |
// eslint-disable-next-line no-param-reassign | |
descriptor.get = () => { | |
if (!has(this, memKey)) { | |
Object.defineProperty(this, memKey, { value: new Map() }) | |
} | |
return this[memKey].has(propertyKey) | |
? this[memKey].get(propertyKey) | |
: (() => { | |
const value = originalGet.call(this) | |
this[memKey].set(propertyKey, value) | |
return value | |
})() | |
} | |
} |
This file contains hidden or 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
[options] | |
unsafe.enable_getters_and_setters=true |
This file contains hidden or 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 memoized from 'util/memoized.decorator' | |
class Example { | |
@memoized | |
get someProperty() { | |
// do something | |
return value | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on http://www.couchcoder.com/using-memoized-decorator-cache-computed-properties/