Sha256: a4649ad4f7afae7c73ba32caee30a819a0c811ce900b42a0cf6aead8bbdc3926

Contents?: true

Size: 722 Bytes

Versions: 16

Compression:

Stored size: 722 Bytes

Contents

require "petrarca/helpers"


module Petrarca
  module ISBN10

    extend self

    def valid?(isbn)
      correct_format?(isbn) && isbn[-1] == calc_check_digit(isbn)
    end

    def correct_format?(isbn)
      isbn = isbn.delete("-")
      !!(/\A\d{9}[0-9X]\z/ =~ isbn)
    end

    def calc_check_digit(isbn)
      nums = isbn.delete("-").split("")[0, 9].map{|x| x.to_i }
      sum = nums.zip((2..10).to_a.reverse).map{|x, y| x * y }.inject(:+)
      check_digit = 11 - (sum % 11)
      case check_digit
      when 10
        "X"
      when 11
        "0"
      else
        check_digit.to_s
      end
    end

    def hyphenate(isbn)
      s = ISBN13.hyphenate("978" + isbn)
      s.sub(/^978-/, "")
    end

  end
end

Version data entries

16 entries across 16 versions & 1 rubygems

Version Path
petrarca-0.4.14 lib/petrarca/isbn10.rb
petrarca-0.4.13 lib/petrarca/isbn10.rb
petrarca-0.4.12 lib/petrarca/isbn10.rb
petrarca-0.4.11 lib/petrarca/isbn10.rb
petrarca-0.4.10 lib/petrarca/isbn10.rb
petrarca-0.4.9 lib/petrarca/isbn10.rb
petrarca-0.4.8 lib/petrarca/isbn10.rb
petrarca-0.4.7 lib/petrarca/isbn10.rb
petrarca-0.4.6 lib/petrarca/isbn10.rb
petrarca-0.4.5 lib/petrarca/isbn10.rb
petrarca-0.4.4 lib/petrarca/isbn10.rb
petrarca-0.4.3 lib/petrarca/isbn10.rb
petrarca-0.4.2 lib/petrarca/isbn10.rb
petrarca-0.4.1 lib/petrarca/isbn10.rb
petrarca-0.4.0 lib/petrarca/isbn10.rb
petrarca-0.3.0 lib/petrarca/isbn10.rb