Sha256: fcb5f471b140cdc21798b3be64db469736848c65e715e7b37d97864413a9cfb4

Contents?: true

Size: 1.05 KB

Versions: 4

Compression:

Stored size: 1.05 KB

Contents

#--
# Credit goes to Robert Feldt.
#++
$MEMOIZE_CACHE = Hash.new
class Module
  # Directive for making your functions faster by trading
  # space for time. When you "memoize" a method/function
  # its results are cached so that later calls with the
  # same arguments returns results in the cache instead
  # of recalculating them. 
  #
  #   require 'facet/module/memoize'
  #  
  #   class T
  #     def initialize(a)
  #       @a = a
  #     end
  #     def a
  #       "#{@a ^ 3 + 4}"
  #     end
  #     memoize :a
  #   end
  #
  #   t = T.new
  #   t.a.__id__  #=>
  #   t.a.__id__  #=>
  #
  def memoize(*methods)
    methods.each do |meth|
      mc = $MEMOIZE_CACHE[meth] = Hash.new
      old = method(meth)
      new = proc {|*args|
        if mc.has_key? args
          mc[args]
        else
          mc[args] = old.call(*args) 
        end
      }
      self.class.send(:define_method, meth, new)
    end
  end
end

# This allows memoize to work in main and instance scope too.
#--
# Is this correct and good?
#++
def memoize(*args)
  self.class.memoize(*args)
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
facets-0.6.3 lib/facet/module/memoize.rb
facets-0.7.0 lib/facet/module/memoize.rb
facets-0.7.1 lib/facet/module/memoize.rb
facets-0.7.2 lib/facet/module/memoize.rb