Class: JSONP3::Path::SliceSelector

Inherits:
Selector
  • Object
show all
Defined in:
lib/json_p3/path/selector.rb

Overview

The slice selector selects a range of elements from an array.

Instance Attribute Summary collapse

Attributes inherited from Selector

#token

Instance Method Summary collapse

Methods inherited from Selector

#resolve_enum, #singular?

Constructor Details

#initialize(env, token, start, stop, step) ⇒ SliceSelector

Returns a new instance of SliceSelector.



189
190
191
192
193
194
# File 'lib/json_p3/path/selector.rb', line 189

def initialize(env, token, start, stop, step)
  super(env, token)
  @start = start
  @stop = stop
  @step = step || 1
end

Instance Attribute Details

#startObject (readonly)

Returns the value of attribute start.



187
188
189
# File 'lib/json_p3/path/selector.rb', line 187

def start
  @start
end

#stepObject (readonly)

Returns the value of attribute step.



187
188
189
# File 'lib/json_p3/path/selector.rb', line 187

def step
  @step
end

#stopObject (readonly)

Returns the value of attribute stop.



187
188
189
# File 'lib/json_p3/path/selector.rb', line 187

def stop
  @stop
end

Instance Method Details

#==(other) ⇒ Object Also known as: eql?



228
229
230
231
232
233
234
# File 'lib/json_p3/path/selector.rb', line 228

def ==(other)
  self.class == other.class &&
    @start == other.start &&
    @stop == other.stop &&
    @step == other.step &&
    @token == other.token
end

#hashObject



238
239
240
# File 'lib/json_p3/path/selector.rb', line 238

def hash
  [@start, @stop, @step, @token].hash
end

#resolve(node) ⇒ Object



196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/json_p3/path/selector.rb', line 196

def resolve(node)
  return [] unless node.value.is_a?(Array)

  length = node.value.length
  return [] if length.zero? || @step.zero?

  normalized_start = if @start.nil?
                       @step.negative? ? length - 1 : 0
                     elsif @start&.negative?
                       [length + (@start || raise), 0].max
                     else
                       [@start || raise, length - 1].min
                     end

  normalized_stop = if @stop.nil?
                      @step.negative? ? -1 : length
                    elsif @stop&.negative?
                      [length + (@stop || raise), -1].max
                    else
                      [@stop || raise, length].min
                    end

  (normalized_start...normalized_stop).step(@step).map { |i| node.new_child(node.value[i], i) }
end

#to_sObject



221
222
223
224
225
226
# File 'lib/json_p3/path/selector.rb', line 221

def to_s
  start = @start || ""
  stop = @stop || ""
  step = @step || 1
  "#{start}:#{stop}:#{step}"
end