Class: Cdigits::Luhn::Store

Inherits:
Object
  • Object
show all
Defined in:
lib/cdigits/luhn/store.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(modulus:, digits: nil) ⇒ Store

Returns a new instance of Store.

Parameters:

  • modulus (Integer)
  • digits (Array<Integer>) (defaults to: nil)

    initial digits (default [])



13
14
15
16
17
# File 'lib/cdigits/luhn/store.rb', line 13

def initialize(modulus:, digits: nil)
  @modulus = modulus
  @digits = digits || []
  @position = nil
end

Instance Attribute Details

#digitsArray<Integer> (readonly)

Returns:

  • (Array<Integer>)


9
10
11
# File 'lib/cdigits/luhn/store.rb', line 9

def digits
  @digits
end

Instance Method Details

#append(value) ⇒ Integer

Append passed value to digits array

Parameters:

  • value (Integer)
  • freeze (Boolean)

Returns:

  • (Integer)

    appended value



50
51
52
53
54
# File 'lib/cdigits/luhn/store.rb', line 50

def append(value)
  table.previsous = value
  @digits << value
  value
end

#append_non_zero_numberInteger

Append random non-zero number to digits array

Returns:

  • (Integer)

    appended value



36
37
38
# File 'lib/cdigits/luhn/store.rb', line 36

def append_non_zero_number
  append table.pick_non_zero
end

#append_numberInteger

Append random number to digits array

Returns:

  • (Integer)

    appended value



42
43
44
# File 'lib/cdigits/luhn/store.rb', line 42

def append_number
  append table.pick
end

#fill_check_digitInteger

Calculate check digit and fill its value into the check digit position

Returns:

  • (Integer)

    check digit



27
28
29
30
31
32
# File 'lib/cdigits/luhn/store.rb', line 27

def fill_check_digit
  return unless @position

  odd = (@digits.size - @position).odd?
  @digits[@position] = calculate_check_digit(sum, odd)
end

#initialize_check_digitObject

Set check digit position



20
21
22
23
# File 'lib/cdigits/luhn/store.rb', line 20

def initialize_check_digit
  @position = @digits.size
  append 0
end

#sumInteger

sum of digits

Returns:

  • (Integer)


58
59
60
61
62
63
# File 'lib/cdigits/luhn/store.rb', line 58

def sum
  digits.reverse.each_with_index.inject(0) do |sum, (value, i)|
    value = double(value) if (i + 1).even?
    sum + value
  end
end