Skip to content

Instantly share code, notes, and snippets.

@kl0tl
Created March 18, 2015 16:12
Show Gist options
  • Save kl0tl/400f1cd46d95be24bc06 to your computer and use it in GitHub Desktop.
Save kl0tl/400f1cd46d95be24bc06 to your computer and use it in GitHub Desktop.
Some fun with the hypothetical ES7 decorators notation (`@xxx`)
class Class {
@Bound
method() {}
@Lazy
get data() {}
}
function Bound(prototype, name, descriptor) {
const { value, writable, enumerable, configurable } = descriptor;
if (typeof value !== 'function') {
throw new Error();
}
const decoratedDescriptor = {
get() { return value.bind(this) }
enumerable, configurable
};
if (writable) decoratedDescriptor.set = function (newValue) {
overrideWith(this, name, newValue)
};
return Lazy(prototype, name, decoratedDescriptor);
}
function Lazy(prototype, name, descriptor) {
const { get, set, enumerable, configurable } = descriptor;
if (typeof get !== 'function') {
throw new Error();
}
const decoratedDescriptor = {
get() {
const value = get.call(this);
overrideWith(this, name, value);
return value;
},
enumerable,
configurable
};
if (set) decoratedDescriptor.set = set;
return decoratedDescriptor;
}
function overrideWith(target, name, value) {
const { set, writable, enumerable, configurable } = Object.getOwnPropertyDescriptor(this, name);
const descriptor = { value, writable: writable || Boolean(set), enumerable, configurable };
Object.defineProperty(this, name, descriptor);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment