diff --git a/@vates/decorate-with/README.md b/@vates/decorate-with/README.md index 861bfd3c5..b5ad3be14 100644 --- a/@vates/decorate-with/README.md +++ b/@vates/decorate-with/README.md @@ -31,6 +31,34 @@ class Foo { } ``` +### `decorateMethodsWith(class, map)` + +Decorates a number of methods directly, without using the decorator syntax: + +```js +import { decorateMethodsWith } from '@vates/decorate-with' + +class Foo { + bar() { + // body + } + + baz() { + // body + } +} + +decorateMethodsWith(Foo, { + // without arguments + bar: lodash.curry, + + // with arguments + baz: [lodash.debounce, 150], +}) +``` + +The decorated class is returned, so you can export it directly. + ## Contributions Contributions are _very_ welcomed, either on the documentation or on diff --git a/@vates/decorate-with/USAGE.md b/@vates/decorate-with/USAGE.md index e304e636f..fb418083f 100644 --- a/@vates/decorate-with/USAGE.md +++ b/@vates/decorate-with/USAGE.md @@ -12,3 +12,31 @@ class Foo { } } ``` + +### `decorateMethodsWith(class, map)` + +Decorates a number of methods directly, without using the decorator syntax: + +```js +import { decorateMethodsWith } from '@vates/decorate-with' + +class Foo { + bar() { + // body + } + + baz() { + // body + } +} + +decorateMethodsWith(Foo, { + // without arguments + bar: lodash.curry, + + // with arguments + baz: [lodash.debounce, 150], +}) +``` + +The decorated class is returned, so you can export it directly. diff --git a/@vates/decorate-with/index.js b/@vates/decorate-with/index.js index c44577de1..8c63013ef 100644 --- a/@vates/decorate-with/index.js +++ b/@vates/decorate-with/index.js @@ -4,3 +4,18 @@ exports.decorateWith = function decorateWith(fn, ...args) { value: fn(descriptor.value, ...args), }) } + +const { getOwnPropertyDescriptor, defineProperty } = Object + +exports.decorateMethodsWith = function decorateMethodsWith(klass, map) { + const { prototype } = klass + for (const name of Object.keys(map)) { + const descriptor = getOwnPropertyDescriptor(prototype, name) + const { value } = descriptor + + const decorator = map[name] + descriptor.value = typeof decorator === 'function' ? decorator(value) : decorator[0](value, ...decorator.slice(1)) + defineProperty(prototype, name, descriptor) + } + return klass +} diff --git a/CHANGELOG.unreleased.md b/CHANGELOG.unreleased.md index 154c5e87a..6d140c77f 100644 --- a/CHANGELOG.unreleased.md +++ b/CHANGELOG.unreleased.md @@ -27,3 +27,5 @@ > - major: if the change breaks compatibility > > In case of conflict, the highest (lowest in previous list) `$version` wins. + +- @vates/decorate-with minor