Created
November 18, 2013 17:14
-
-
Save psstoev/7531555 to your computer and use it in GitHub Desktop.
Memoize solutions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Solution 1: | |
class Memoizer < BasicObject | |
def initialize(instance) | |
@instance = instance | |
@cache = {} | |
end | |
def cache(method, *args) | |
@cache["#{method}, #{args}"] = @instance.public_send method, *args | |
end | |
def memoize(method, *args) | |
@cache["#{method}, #{args}"] || cache(method, *args) | |
end | |
def method_missing(method, *args, &block) | |
if ::Kernel.send :block_given? | |
return @instance.public_send method, *args, &block | |
else | |
memoize method, *args | |
end | |
end | |
private :cache, :memoize | |
end | |
# Solution 2: | |
class Memoizer < BasicObject | |
def initialize(target) | |
@target = target | |
@cache = {} | |
end | |
def method_missing(method, *args, &block) | |
if @target.respond_to? method | |
key = "#{method}, #{args}" | |
return @cache[key] if @cache.has_key? key | |
value = @target.public_send method, *args, &block | |
block.nil? ? @cache[key] = value : value | |
else | |
::Kernel.raise ::NoMethodError | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment