Last active
August 14, 2021 11:51
-
-
Save JoshCheek/c03350076650d29e7db6c65e81e80951 to your computer and use it in GitHub Desktop.
Memoizing a method with an optional default value without receiving splat args
This file contains hidden or 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
| module Memoize | |
| NOT_SET = Module.new | |
| private_constant :NOT_SET | |
| def memoize(method_name) | |
| meth = method method_name | |
| case meth.parameters.map(&:first) | |
| when [:opt] | |
| define_method method_name do |arg=NOT_SET| | |
| _memoizations.fetch arg do | |
| _memoizations[arg] = (arg == NOT_SET ? meth.call : meth.call(arg)) | |
| end | |
| end | |
| else | |
| raise 'unoptimized path goes here' | |
| end | |
| end | |
| private def _memoizations | |
| @_memoizations ||= {} | |
| end | |
| end | |
| extend Memoize | |
| memoize def greeting(name='world') | |
| name # => "world", "Josh" | |
| "Hello, #{name}" | |
| end | |
| greeting # => "Hello, world" | |
| greeting # => "Hello, world" | |
| greeting 'Josh' # => "Hello, Josh" | |
| greeting 'Josh' # => "Hello, Josh" | |
| _memoizations # => {Memoize::NOT_SET=>"Hello, world", "Josh"=>"Hello, Josh"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment