Module: Sjekksum::Damm

Extended by:
Damm, Shared
Included in:
Damm
Defined in:
lib/sjekksum/damm.rb

Overview

Module for calculation and validation of Damm checksums

See Also:

Constant Summary collapse

QUASIGROUP =

The totally anti-symmetric quasigroup

[
  [ 0, 3, 1, 7, 5, 9, 8, 6, 4, 2 ],
  [ 7, 0, 9, 2, 1, 5, 4, 8, 6, 3 ],
  [ 4, 2, 0, 6, 8, 7, 1, 3, 5, 9 ],
  [ 1, 7, 5, 0, 9, 8, 3, 4, 2, 6 ],
  [ 6, 1, 2, 3, 0, 4, 5, 9, 7, 8 ],
  [ 3, 6, 7, 4, 2, 0, 9, 5, 8, 1 ],
  [ 5, 8, 6, 9, 7, 2, 0, 1, 3, 4 ],
  [ 8, 9, 4, 5, 3, 6, 2, 0, 1, 7 ],
  [ 9, 4, 3, 8, 6, 1, 7, 2, 0, 5 ],
  [ 2, 5, 8, 1, 4, 3, 6, 7, 9, 0 ]
].freeze

Instance Method Summary collapse

Instance Method Details

#convert(number) ⇒ Integer, String Also known as: transform

Transforms a number by appending the Damm checksum digit

Examples:

Sjekksum::Damm.convert(572) #=> 5724

Parameters:

  • number (Integer, String)

    number without a checksum

Returns:

  • (Integer, String)

    final number including the checksum


66
67
68
69
# File 'lib/sjekksum/damm.rb', line 66

def convert number
  raise_on_type_mismatch number
  typed_conversion number
end

#of(number) ⇒ Integer Also known as: checksum

Calculates Damm checksum

Examples:

Sjekksum::Damm.of(572) #=> 4

Parameters:

  • number (Integer, String)

    number for which the checksum should be calculated

Returns:

  • (Integer)

    calculated checksum


35
36
37
38
39
# File 'lib/sjekksum/damm.rb', line 35

def of number
  raise_on_type_mismatch number
  digits = convert_number_to_digits(number)
  digits.reduce(0){ |check, digit| QUASIGROUP[check][digit] }
end

#valid?(number) ⇒ Boolean Also known as: is_valid?

Damm validation of provided number

Examples:

Sjekksum::Damm.valid?(5724) #=> true

Parameters:

  • number (Integer, String)

    number with included checksum

Returns:

  • (Boolean)

51
52
53
54
# File 'lib/sjekksum/damm.rb', line 51

def valid? number
  raise_on_type_mismatch number
  self.of(number).zero?
end