Class: JSI::Util::Private::MemoMap Private

Inherits:
Object
  • Object
show all
Defined in:
lib/jsi/util/private.rb

This class is part of a private API. You should avoid using this class if possible, as it may be removed or be changed in the future.

Defined Under Namespace

Classes: Result

Instance Method Summary collapse

Constructor Details

#initialize(key_by: nil, &block) ⇒ MemoMap

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a new instance of MemoMap.



116
117
118
119
120
121
122
123
124
125
126
# File 'lib/jsi/util/private.rb', line 116

def initialize(key_by: nil, &block)
  @key_by = key_by
  @block = block

  # each result has its own mutex to update its memoized value thread-safely
  @result_mutexes = {}
  # another mutex to thread-safely initialize each result mutex
  @result_mutexes_mutex = Mutex.new

  @results = {}
end

Instance Method Details

#[](**inputs) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/jsi/util/private.rb', line 128

def [](**inputs)
  if @key_by
    key = @key_by.call(**inputs)
  else
    key = inputs
  end
  result_mutex = @result_mutexes_mutex.synchronize do
    @result_mutexes[key] ||= Mutex.new
  end

  result_mutex.synchronize do
    inputs_hash = inputs.hash
    if @results.key?(key) && inputs_hash == @results[key].inputs_hash && inputs == @results[key].inputs
      @results[key].value
    else
      value = @block.call(**inputs)
      @results[key] = Result.new(value: value, inputs: inputs, inputs_hash: inputs_hash)
      value
    end
  end
end