Created
November 14, 2015 23:15
-
-
Save trajing/cec69ec50a8767a97b6d to your computer and use it in GitHub Desktop.
Ruby Simple Memoization
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
# Play with this at https://eval.in/468799 | |
class Memoizer | |
class MemoEmpty; end | |
def initialize(proc = nil, &block) # I should write something to make this easier as well. | |
@marker == MemoEmpty.new | |
@cache = {} | |
@cache.default = @marker | |
if block_given? | |
@block = block | |
elsif proc | |
@block = proc | |
else | |
raise ArgumentError, 'must give proc or block' | |
end | |
end | |
def call(*args) | |
if @cache[args].object_id == @marker.object_id | |
@cache[args] = @block[*args] | |
end | |
@cache[args] | |
end | |
alias_method :[], :call | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment