Class: Vindetta::Calculator

Inherits:
Object
  • Object
show all
Defined in:
lib/vindetta/calculator.rb

Constant Summary collapse

InvalidCharacterError =
Class.new(StandardError)

Class Method Summary collapse

Class Method Details

.check_digit(vin) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/vindetta/calculator.rb', line 7

def self.check_digit(vin)
  transliterator = lambda do |c|
    index = "0123456789.ABCDEFGH..JKLMN.P.R..STUVWXYZ".chars.index(c)

    raise InvalidCharacterError if index.nil?

    index % 10
  end

  summer = lambda do |sum, (a, b)|
    sum + (a * b)
  end

  sum = vin
        .chars
        .map(&transliterator)
        .zip([8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2])
        .reduce(0, &summer)

  "0123456789X"[sum % 11]
end