0

Am using legacy decorators for decorating a function in such a way that all props given to that decorator will be applied to the last optional argument of the function. Decorator code:

export function dec(props){
  return (target, property, descriptor) => {
    //Note: WIP!! Does not work for all scenarios!
    var fn = descriptor.value;
    descriptor.value = function () {
      if(!arguments.length) return fn.apply(this,new Array(props));
      let [last, ...first] = [...arguments].reverse();
      last = Object.assign(last, props);
      return fn.apply(this, [...([...first].reverse()), last]);
    };
};

}

Base API definition :

funcA ( data, opts = {}) { /*funcA body*/ }
funcB ( id, data, opts = {}) { /*funcB body*/ }
funcB ( opts = {}) { /*funcC body*/ }

Wrapper class function definitions:

 @({ k1: 'v1'})
 wrapFuncA(data, opts = {} /*optional*/){
    return this.funcA(id, opts);
 }

 @({ k1: 'v1'})
 wrapFuncB(id, data, opts = {} /*optional*/){
    return this.funcB(id, data, opts);
 }

 @({ k1: 'v1'})
 wrapFuncC(opts = {} /*optional*/){
    return this.funcC(opts);
 }

Invocation use cases:

  1. wrapFuncA(1); // will invoke: funcA(1,{ k1: 'v1'})
  2. wrapFuncB(1, dObj, {k2: 'v2'}); // will invoke: funcB(1, dObj, { k1: 'v1', k2: 'v2'})
  3. wrapFuncB(1, dObj); // will invoke: funcB(1, dObj, { k1: 'v1'})
  4. wrapFuncC({k3:'v3'}); // will invoke: funcC({ k1: 'v1'},{ k3: 'v3'})

The general logic would be: Take the last argument and extend it with decorator props. However, because of the requirement of last argument being optional, this will fail in case of 3 above.

Any suggestion on how to solve this would he appreciated. Thanks.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
CodeRain
  • 6,334
  • 4
  • 28
  • 33

0 Answers0