Sha256: f646e36a623a7c3c6af7eaf209452842b2369e1b66b09961d26b21089dc81abb

Contents?: true

Size: 1.66 KB

Versions: 20

Compression:

Stored size: 1.66 KB

Contents

#--
# Credit goes to Robert Feldt.
#++

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.
  #
  #   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__  #=> true
  #
  def memoize(*meths)
    @_MEMOIZE_CACHE ||= Hash.new
    meths.each do |meth|
      mc = @_MEMOIZE_CACHE[meth] = Hash.new
      old = instance_method(meth)
      new = proc do |*args|
        if mc.has_key? args
          mc[args]
        else
          mc[args] = old.bind(self).call(*args)
        end
      end
      send(:define_method, meth, &new)
    end
  end

end

# This allows memoize to work in main and instance scope too.
#--
# Would this be good to have? Will need to modify for instance level, if so.
#++
#def memoize(*args)
#  self.class.memoize(*args)
#end


#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
=begin test

  require 'test/unit'

  class T
    def initialize(a)
      @a = a
    end
    def a
      "#{@a ^ 3 + 4}"
    end
    memoize :a
  end

  # test

  class TC_Memoize < Test::Unit::TestCase

    def setup
      @t = T.new(2)
    end

    def test_memoize_01
      assert_equal( @t.a, @t.a )
    end

    def test_memoize_02
      assert_equal( @t.a.__id__, @t.a.__id__ )
    end

    def test_memoize_03
      assert_equal( @t.a.__id__, @t.a.__id__ )
    end

  end

=end

Version data entries

20 entries across 20 versions & 1 rubygems

Version Path
facets-1.0.0 lib/facet/module/memoize.rb
facets-0.9.0 lib/nano/module/memoize.rb
facets-1.0.3 packages/core/lib/facet/module/memoize.rb
facets-1.2.1 lib/facets/core/module/memoize.rb
facets-1.2.0 lib/facets/core/module/memoize.rb
facets-1.3.0 lib/facets/core/module/memoize.rb
facets-1.1.0 lib/facet/module/memoize.rb
facets-1.3.1 lib/facets/core/module/memoize.rb
facets-1.3.3 lib/facets/core/module/memoize.rb
facets-1.3.2 lib/facets/core/module/memoize.rb
facets-1.4.1 lib/facets/core/module/memoize.rb
facets-1.4.0 lib/facets/core/module/memoize.rb
facets-1.4.2 lib/facets/core/module/memoize.rb
facets-1.4.3 lib/facets/core/module/memoize.rb
facets-1.4.4 lib/facets/core/module/memoize.rb
facets-1.4.5 lib/facets/core/module/memoize.rb
facets-1.7.0 lib/facets/core/module/memoize.rb
facets-1.7.30 lib/facets/core/module/memoize.rb
facets-1.7.38 lib/facets/core/module/memoize.rb
facets-1.7.46 lib/facets/core/module/memoize.rb