method-cache
v1.0.0
Published
memoization for object methods with a coffee focus
Downloads
1
Readme
method-cache
I micro library that provides a simple method cache that works well with CoffeeScript class methods and can be used in an annotation style or as a mixin.
All memoized method definitions are a variation on a basic signature:
# cacheName - (mandatory) name of the field on the context object to use as the cache
# func - (mandatory) method implementation
# resolver - optional cache key derivation function
(cacheName, func, resolver) ->
The basic, verbose, usage is:
cache = require('method-cache').cacheMethod
TestClass = class
doit1: cache '__doit1', (arg1, arg2) -> "#{arg1},#{arg2}"
doit2: cache '__doit2', (arg1, arg2) ->
"#{arg1},#{arg2}"
, (arg1, arg2) -> arg2
Alternatively methods can be defined in an "annotation" style:
cache = require('method-cache').annotate
TestClass = class
doit1: cache('__doit1') (arg1, arg2) -> "#{arg1},#{arg2}"
doit2: cache('__doit2') (arg1, arg2) ->
"#{arg1},#{arg2}"
, (arg1, arg2) -> arg2
# specifying resolver in annotation
doit3: cache('__doit3', (arg1, arg2) -> arg2) (arg1, arg2) ->
"#{arg1},#{arg2}"
Methods can be defined directly on the prototype via the shorthand:
define = (proto, name) ->
Example:
cache = require('../index').define
TestClass = class
cache(@::, 'doit1') (arg1, arg2) -> "#{arg1},#{arg2}"
cache(@::, 'doit2') (arg1, arg2) ->
"#{arg1},#{arg2}"
, (arg1, arg2) -> arg2
To specify the resolver function first, use defineWithResolver
:
cache = require('../index').defineWithResolver
TestClass = class
cache(@::, 'doit1') (arg1, arg2) -> "#{arg1},#{arg2}"
cache(@::, 'doit2', (arg1, arg2) -> arg2) (arg1, arg2) ->
"#{arg1},#{arg2}"
Finally, specifying the prototype can be avoided by using a mixin:
cachable = require('method-cache').cachable
TestClass = class
_.extend @, cachable
@cacheMethod('doit1') (arg1, arg2) -> "#{arg1},#{arg2}"
@cacheMethod('doit2') (arg1, arg2) ->
"#{arg1},#{arg2}"
, (arg1, arg2) -> arg2
# specifying resolver in definition function
@cacheMethod('doit3', (arg1, arg2) -> arg2) (arg1, arg2) ->
"#{arg1},#{arg2}"