Class: FractionalIndexer::Decrementer

Inherits:
Object
  • Object
show all
Defined in:
lib/fractional_indexer/decrementer.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.execute(order_key) ⇒ Object



5
6
7
# File 'lib/fractional_indexer/decrementer.rb', line 5

def self.execute(order_key)
  new.execute(order_key)
end

Instance Method Details

#execute(order_key) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/fractional_indexer/decrementer.rb', line 9

def execute(order_key)
  prefix, *digs = order_key.integer.chars
  borrow = true

  (digs.length - 1).downto(0) do |i|
    decremented_index = digits.index(digs[i]) - 1

    if borrow?(decremented_index)
      digs[i] = digits[-1]
    else
      digs[i] = digits[decremented_index]
      borrow  = false

      break
    end
  end

  return prefix + digs.join unless borrow

  return "Z#{digits[-1]}" if prefix == "a"
  return if prefix == "A"

  new_key = (prefix.ord - 1).chr
  new_key < "Z" ? digs.push(digits[-1]) : digs.pop

  new_key + digs.join
end