2 require "decorate/create_alias"
4 module Decorate::Memoize
6 # A naive memoization decorator, using a plain Hash as cache.
10 # require "decorate/memoize"
12 # Decorate::Memoize.memoize
14 # n == 0 ? 1 : n * factorial(n - 1)
16 # factorial(7) # => 5040
18 # Memoization takes the arguments as well as the instance itself
19 # into account. You can also extend a module/class with
20 # Decorate::Memoize to leave off the module prefix. Note that this
21 # decorator doesn't work for methods that take a block.
23 Decorate.decorate { |klass, method_name|
24 wrapped_method_name = Decorate.create_alias(klass, method_name, :memoize)
25 # TODO: should use weak hash tables
26 cache = Hash.new { |hash, key| hash[key] = {} }
27 klass.send(:define_method, method_name) { |*args|
29 if icache.has_key?(args)
32 icache[args] = send(wrapped_method_name, *args)
37 module_function :memoize