Class: Reacto::Operations::Slice

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

Constant Summary collapse

TYPES =
%i(before after)

Instance Method Summary collapse

Constructor Details

#initialize(predicate, type: :after) ⇒ Slice

Returns a new instance of Slice.



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

def initialize(predicate, type: :after)
  unless TYPES.include?(type)
    raise ArgumentError.new(
      "Type #{type} not supported. " \
      "Supported types are #{TYPES.join(', ')}"
    )
  end

  @type = type
  @predicate = predicate
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
41
42
43
44
45
46
47
# File 'lib/reacto/operations/slice.rb', line 20

def call(tracker)
  buffer = []

  behaviour = -> (val) do
    buffer << val if @type == :after

    if @predicate.call(val)
      tracker.on_value(Trackable.enumerable(buffer))
      buffer = []
    end

    buffer << val if @type == :before
  end

  error = -> (e) do
    tracker.on_value(Trackable.enumerable(buffer)) unless buffer.empty?
    tracker.on_error(e)
  end

  close = -> () do
    tracker.on_value(Trackable.enumerable(buffer)) unless buffer.empty?
    tracker.on_close
  end

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