isbn check looks ok

This commit is contained in:
remy 2020-04-25 14:08:46 +02:00
parent e4402fbf66
commit 43de6c1949

122
src/main.cr Normal file
View File

@ -0,0 +1,122 @@
require "json"
# This will check if the ISBN is valid
# https://en.wikipedia.org/wiki/International_Standard_Book_Number#Check_digits
a = "978-0-306-40615"
b = "12-31231 23.1aa"
c = "0-306-406v155"
isbn10 = "2234086167"
isbn13 = "978-2234086166"
def remove_hyphen_space(isbn_code)
isbn_code = isbn_code.gsub(/[- .]/, "")
return isbn_code
end
def is_valid_isbn(isbn_code)
isbn_code = remove_hyphen_space(isbn_code)
array = isbn_code.chars
pp array
if isbn_code =~ /^[0-9]*$/
pp "ok number only"
if isbn_code.size == 10
pp "isbn10"
pp "check_digit_isbn10"
i = check = 0
t = 10
while i < 9
check = array[i].to_i * (t - i) + check
i = i + 1
end
pp result = ( 11 - (check % 11)) % 11
if (result - array[9].to_i) == 0
pp "isbn10 is ok"
else
pp "isbn10 check key fail"
end
elsif isbn_code.size ==13
pp "isbn13"
pp "check_digit_isbn13"
i = check = 0
while i < 12
if i % 2 == 0
check = array[i].to_i + check
else
check = 3 * array[i].to_i + check
end
i = i + 1
end
pp result = 10 - (check % 10)
if result - array[12].to_i == 0
pp "isbn13 is ok"
else
pp "isbn13 check key fail"
end
else
pp "wrong size"
return false
end
else
pp "ko not only number"
return false
end
end
#array.each do |x|
# x = x.to_i8?
# case x
# when Int8
# else
# pp "error"
# end
# end
#end
is_valid_isbn(isbn10)
is_valid_isbn(isbn13)
is_valid_isbn(c)
is_valid_isbn(a)
is_valid_isbn(b)
# from oder source
class ISBN::IsValid
def self.new(isbn : String)
# Check to make sure string has valid encoding and raise execption if not
raise Exceptions::Generic.new("ISBN isn't valid") unless isbn.valid_encoding?
# Remove `-` characters since we want to properly check value
if (isbn =~ /-/)
isbn = isbn.split(/-/).join
end
case isbn.size
when 10
ISBN::IsValid.valid_isbn_10(isbn)
when 13
ISBN::IsValid.valid_isbn_13(isbn)
else
false
end
end
# There's probably a more elegant way to do the defs below
# Return false if numbers aren't correct
def self.valid_isbn_10(isbn : String)
return false unless isbn.match(/^[0-9]{9}[0-9X]$/)
return true
end
def self.valid_isbn_13(isbn : String)
return false unless isbn.match(/^[0-9]{12}[0-9X]$/)
return true
end
end