Class: Reacto::Operations::Extremums

Inherits:
Object
  • Object
show all
Defined in:
lib/reacto/operations/extremums.rb

Constant Summary collapse

AVAILABLE_TYPES =
%i(min max minmax)

Instance Method Summary collapse

Constructor Details

#initialize(action: nil, by: nil, type: :max) ⇒ Extremums

Returns a new instance of Extremums.



8
9
10
11
12
13
14
15
16
17
18
# File 'lib/reacto/operations/extremums.rb', line 8

def initialize(action: nil, by: nil, type: :max)
  unless AVAILABLE_TYPES.include?(type)
    raise ArgumentError.new(
      "Type not supported, expecting one of #{AVAILABLE_TYPES.join(', ')}"
    )
  end

  @action = action
  @by = by
  @type = type
end

Instance Method Details

#call(tracker) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/reacto/operations/extremums.rb', line 20

def call(tracker)
  buffer = []

  behaviour = -> (v) do
    buffer << v
  end

  error = -> (e) do
    emit_values(tracker, buffer)
    tracker.on_error(e)
  end

  close = -> () do
    emit_values(tracker, buffer)
    tracker.on_close
  end

  Subscriptions::OperationSubscription.new(
    tracker, error: error, value: behaviour, close: close
  )
end

#emit_values(tracker, buffer) ⇒ Object



42
43
44
45
46
47
48
49
50
51
# File 'lib/reacto/operations/extremums.rb', line 42

def emit_values(tracker, buffer)
  values =
    if @by
      buffer.send("#{@type.to_s}_by", &@by)
    else
      buffer.send(@type, &@action)
    end

  Array(values).each { |val| tracker.on_value(val) }
end