feat(decorate-with): perInstance helper
This commit is contained in:
parent
a07c5418e9
commit
02da7c272f
@ -70,6 +70,25 @@ decorateMethodsWith(Foo, {
|
|||||||
})
|
})
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### `perInstance(fn, ...args)`
|
||||||
|
|
||||||
|
Helper to decorate the method by instance instead of for the whole class.
|
||||||
|
|
||||||
|
This is often necessary for caching or deduplicating calls.
|
||||||
|
|
||||||
|
```js
|
||||||
|
import { perInstance } from '@vates/decorateWith'
|
||||||
|
|
||||||
|
class Foo {
|
||||||
|
@decorateWith(perInstance, lodash.memoize)
|
||||||
|
bar() {
|
||||||
|
// body
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Because it's a normal function, it can also be used with `decorateMethodsWith`, with `compose` or even by itself.
|
||||||
|
|
||||||
## Contributions
|
## Contributions
|
||||||
|
|
||||||
Contributions are _very_ welcomed, either on the documentation or on
|
Contributions are _very_ welcomed, either on the documentation or on
|
||||||
|
@ -51,3 +51,22 @@ decorateMethodsWith(Foo, {
|
|||||||
])
|
])
|
||||||
})
|
})
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### `perInstance(fn, ...args)`
|
||||||
|
|
||||||
|
Helper to decorate the method by instance instead of for the whole class.
|
||||||
|
|
||||||
|
This is often necessary for caching or deduplicating calls.
|
||||||
|
|
||||||
|
```js
|
||||||
|
import { perInstance } from '@vates/decorateWith'
|
||||||
|
|
||||||
|
class Foo {
|
||||||
|
@decorateWith(perInstance, lodash.memoize)
|
||||||
|
bar() {
|
||||||
|
// body
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Because it's a normal function, it can also be used with `decorateMethodsWith`, with `compose` or even by itself.
|
||||||
|
@ -19,3 +19,15 @@ exports.decorateMethodsWith = function decorateMethodsWith(klass, map) {
|
|||||||
}
|
}
|
||||||
return klass
|
return klass
|
||||||
}
|
}
|
||||||
|
|
||||||
|
exports.perInstance = function perInstance(fn, decorator, ...args) {
|
||||||
|
const map = new WeakMap()
|
||||||
|
return function () {
|
||||||
|
let decorated = map.get(this)
|
||||||
|
if (decorated === undefined) {
|
||||||
|
decorated = decorator(fn, ...args)
|
||||||
|
map.set(this, decorated)
|
||||||
|
}
|
||||||
|
return decorated.apply(this, arguments)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user