Sha256: 87a81b39c1df4a8c655230b888c8dac67cfff8b7abc1620db2bcc324ead78df1

Contents?: true

Size: 544 Bytes

Versions: 3

Compression:

Stored size: 544 Bytes

Contents

module BrDocuments
  class Gtin
    def initialize(code)
      @code = code
    end

    def valid?
      valid_length? && valid_checksum?
    end

    private

    def valid_length?
      [8, 12, 13, 14].include?(@code.length)
    end

    def valid_checksum?
      numbers = @code.chars[0, @code.length - 1].reverse
      odd = even = 0

      numbers.each_with_index do |number, i|
        (i + 1).even? ? (even += number.to_i) : (odd += number.to_i * 3)
      end

      @code.chars.last.to_i == ((10 - (odd + even)) % 10)
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
br_documents-0.1.3 lib/br_documents/gtin/gtin.rb
br_documents-0.1.2 lib/br_documents/gtin/gtin.rb
br_documents-0.1.1 lib/br_documents/gtin/gtin.rb