Module: Async::Enumerable::Methods::Predicates::FindIndex
- Defined in:
- lib/async/enumerable/methods/predicates/find_index.rb
Class Method Summary collapse
Instance Method Summary collapse
-
#find_index(value = (no_value = true), &block) ⇒ Integer?
Returns index of first matching element (parallel, early termination).
Class Method Details
.included(base) ⇒ Object
8 9 10 11 12 |
# File 'lib/async/enumerable/methods/predicates/find_index.rb', line 8 def self.included(base) base.include(::Enumerable) # Dependency base.include(Configurable) # Dependency for collection resolution base.include(ConcurrencyBounder) # Dependency end |
Instance Method Details
#find_index(value = (no_value = true), &block) ⇒ Integer?
Note:
Returns the index of the fastest completing match, not necessarily the first by position.
Due to parallel execution, whichever element completes evaluation first will have its index returned.
Use synchronous find_index if positional order matters.
Returns index of first matching element (parallel, early termination).
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/async/enumerable/methods/predicates/find_index.rb', line 20 def find_index(value = (no_value = true), &block) if no_value && !block_given? return enum_for(__method__) end result_index = Concurrent::AtomicReference.new(nil) __async_enumerable_bounded_concurrency(early_termination: true) do || __async_enumerable_collection.each_with_index do |item, index| break unless result_index.get.nil? .async do match = no_value ? block.call(item) : (item == value) if match # Use compare_and_set to ensure only the first match wins if result_index.compare_and_set(nil, index) # Stop the barrier early when we find a match .stop end end end end end result_index.get end |