class Cdigits::Luhn::Store

Attributes

digits[R]

@return [Array<Integer>]

Public Class Methods

new(modulus:, digits: nil) click to toggle source

@param [Integer] modulus @param [Array<Integer>] digits initial digits (default [])

# File lib/cdigits/luhn/store.rb, line 13
def initialize(modulus:, digits: nil)
  @modulus = modulus
  @digits = digits || []
  @position = nil
end

Public Instance Methods

append(value) click to toggle source

Append passed value to digits array @param value [Integer] @param freeze [Boolean] @return [Integer] appended value

# File lib/cdigits/luhn/store.rb, line 50
def append(value)
  table.previsous = value
  @digits << value
  value
end
append_non_zero_number() click to toggle source

Append random non-zero number to digits array @return [Integer] appended value

# File lib/cdigits/luhn/store.rb, line 36
def append_non_zero_number
  append table.pick_non_zero
end
append_number() click to toggle source

Append random number to digits array @return [Integer] appended value

# File lib/cdigits/luhn/store.rb, line 42
def append_number
  append table.pick
end
fill_check_digit() click to toggle source

Calculate check digit and fill its value into the check digit position @return [Integer] check digit

# 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_digit() click to toggle source

Set check digit position

# File lib/cdigits/luhn/store.rb, line 20
def initialize_check_digit
  @position = @digits.size
  append 0
end
sum() click to toggle source

sum of digits @return [Integer]

# 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

Private Instance Methods

calculate_check_digit(value, odd) click to toggle source
# File lib/cdigits/luhn/store.rb, line 71
def calculate_check_digit(value, odd)
  mod = value % @modulus
  return 0 if mod.zero?

  check_digit = @modulus - mod
  return check_digit if odd

  check_digit += @modulus - 1 if check_digit.odd?
  check_digit / 2
end
double(num) click to toggle source

@example

# num = 6, modulus = 10
# (12 / 10) + (12 % 10) = 3
double(6) # => 3

@example

# num = 12, modulus = 16
# (24 / 16) + (24 % 16) = 9
double(12) # => 9
# File lib/cdigits/luhn/store.rb, line 90
def double(num)
  num *= 2
  (num / @modulus).to_i + (num % @modulus)
end
table() click to toggle source
# File lib/cdigits/luhn/store.rb, line 67
def table
  @table ||= ::Cdigits::Luhn::RandomTable.new(modulus: @modulus)
end