memoize
Version 2.x
memoize
is a classic AOP helper, which caches a result value of a method helping to speed up calculations.
It is defined in dcl/advices/memoize.js
.
Description
The module provides two public functions described below. Those functions can defined a property on an instance called __memoizerCache
.
This is an API of the module:
1 2 3 4 |
|
advice(name, keyMaker)
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 anarguments
object, which was used to call our method.
keyMaker
should return an 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().
Examples
Class-level example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
|
Object-level example:
1 2 3 4 5 6 7 8 9 10 |
|
More complex example with Ackermann function and keyMaker
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
|