developit / decko

:dash: The 3 most useful ES7 decorators: bind, debounce and memoize
https://developit.github.io/decko/
MIT License
1.03k stars 36 forks source link

Is memoize supposed to work on getters? #15

Open jrmyio opened 6 years ago

jrmyio commented 6 years ago

(tested in Typescript)

import { memoize } from 'decko';

class Stores(){
}

class Container {

    @memoize
    public get stores () {
        return new Stores();
    }
}

Throws an error: ​​Invalid property descriptor. Cannot both specify accessors and a value or writable attribute, #<Object>​​

For reference: https://github.com/darrylhodgins/typescript-memoize does work.

kiruh commented 6 years ago

No, it's not working with getters since decorator method in source code doesn't check if you're applying decorator on regular method or getter:

function decorator(fn) {
    return opt => (
        typeof opt==='function' ? fn(opt) : (target, key, desc) => {
            desc.value = fn(desc.value, opt, target, key, desc);
        }
    );
}

This would work with getters:

function decorator(fn) {
    return opt => (
        typeof opt==='function' ? fn(opt) : (target, key, desc) => {
            if (desc.value) desc.value = fn(desc.value, opt, target, key, desc);
            if (desc.get) desc.get = fn(desc.get, opt, target, key, desc);
        }
    );
}
developit commented 6 years ago

PR welcome!