This method creates an advice object that can bypass the original method,
if its result for a given combination of parameters is already cached.
name is a unique name identifying an object-level cache for the method.
Usually it is a method name. If you reuse the same name for different methods
of the same object, make sure that those methods are logically the same and
return the same values.
keyMaker is an optional parameter. It is a function, which takes two arguments:
instance, which is an object we operate on.
args, which is an arguments object, which was used to call our method.
keyMaker should return a hashable object (usually a string) that uniquely
identifies the combination of arguments in cache. If keyMaker is not present,
the first arguments’ string representation is used as a cache key.
The return value of advice() is an advice object, which can be used directly
with dcl.advise() or advise().
guard(name)
This method creates an advice object that clears the named cache.
name parameter indicates, which cache we want to clear on an object. This name
is the same as used by advice(name, keyMaker).
It returns an advice object, which can be used directly with
dcl.advise() or advise().
varStack=dcl(null,{declaredClass:"Stack",constructor:function(){this.stack=[];},push:function(n){returnthis.stack.push(n);},pop:function(){returnthis.stack.pop();},sum:function(init){// expensive, yet frequently called method// it has a linear complexity on stack sizevaracc=init;for(vari=0;i<this.stack.length;++i){acc+=this.stack[i];}returnacc;}});// let's speed it up!varInstrumentedStack=dcl(Stack,{declaredClass:"InstrumentedStack",// sum() should be cachedsum:dcl.advise(memoize.advice("sum")),// but it will change when more numbers// pushed and popped => reset cachepush:dcl.advise(memoize.guard("sum")),pop:dcl.advise(memoize.guard("sum"))});varx=newInstrumentedStack();
varStack=dcl(null,{declaredClass:"Stack",constructor:function(){this.stack=[];},push:function(n){returnthis.stack.push(n);},pop:function(){returnthis.stack.pop();},sum:function(init){// expensive, yet frequently called method// it has a linear complexity on stack sizevaracc=init;for(vari=0;i<this.stack.length;++i){acc+=this.stack[i];}returnacc;}});// our instancevarx=newStack();// let's speed it up!// sum() should be cachedadvise(x,"sum",memoize.advice("sum"));// but it will change when more numbers// pushed and popped => reset cacheadvise(x,"push",memoize.guard("sum"));advise(x,"pop",memoize.guard("sum"));
More complex example with Ackermann function and keyMaker: