From 43de6c1949bafc83c1ac46c9c4f4baf2ad5eb6c8 Mon Sep 17 00:00:00 2001 From: remy Date: Sat, 25 Apr 2020 14:08:46 +0200 Subject: [PATCH] isbn check looks ok --- src/main.cr | 122 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 src/main.cr diff --git a/src/main.cr b/src/main.cr new file mode 100644 index 0000000..d69bd3c --- /dev/null +++ b/src/main.cr @@ -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