Class: Janeway::Interpreters::ArraySliceSelectorInterpreter

Inherits:
Base
  • Object
show all
Defined in:
lib/janeway/interpreters/array_slice_selector_interpreter.rb

Overview

Interprets array slice selector on the given input

Constant Summary

Constants inherited from Base

Base::NOTHING

Instance Attribute Summary

Attributes inherited from Base

#next, #node

Instance Method Summary collapse

Methods inherited from Base

#initialize, #to_s, #type

Constructor Details

This class inherits a constructor from Janeway::Interpreters::Base

Instance Method Details

#as_jsonHash

Returns:

  • (Hash)


44
45
46
# File 'lib/janeway/interpreters/array_slice_selector_interpreter.rb', line 44

def as_json
  { type: type, value: node.to_s, next: @next&.as_json }.compact
end

#interpret(input, _parent, root, path) ⇒ Array

Filter the input by applying the array slice selector.

Parameters:

  • input (Array, Hash)

    the results of processing so far

  • _parent (Array, Hash)

    parent of the input object

  • root (Array, Hash)

    the entire input

  • path (Array<String>)

    elements of normalized path to the current input

Returns:

  • (Array)


18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/janeway/interpreters/array_slice_selector_interpreter.rb', line 18

def interpret(input, _parent, root, path)
  return [] unless input.is_a?(Array)
  return [] if selector&.step&.zero? # RFC: When step is 0, no elements are selected.

  # Calculate the upper and lower indices of the target range
  lower = selector.lower_index(input.size)
  upper = selector.upper_index(input.size)

  # Collect real index values. Omit the final index, since no value is collected for that.
  indexes =
    if selector.step.positive?
      lower.step(to: upper - 1, by: selector.step).to_a
    else
      upper.step(to: lower + 1, by: selector.step).to_a
    end
  return indexes.map { |i| input[i] } unless @next

  # Apply child selector to each node in the output node list
  results = []
  indexes.each do |i|
    results.concat @next.interpret(input[i], input, root, path + [i])
  end
  results
end