Added Faker::Code.isbn

This commit is contained in:
Egor Romanov 2022-02-16 22:31:59 +03:00
parent 9f8608f7cd
commit e2c95c114d
3 changed files with 55 additions and 0 deletions

View File

@ -79,6 +79,15 @@ Faker::Business.credit_card_type #=> "visa"
```
### Faker::Code
```crystal
Faker::Code.isbn #=> 640354399-7
```
### Faker::Commerce
```crystal

17
spec/code_spec.cr Normal file
View File

@ -0,0 +1,17 @@
require "./spec_helper"
describe Faker::Code do
it "base 10 isbn" do
Faker::Code.isbn.match(/^\d{9}-[\d|X]$/).should_not eq nil
end
it "base 13 isbn" do
Faker::Code.isbn(13).match(/^\d{12}-\d$/).should_not eq nil
end
it "should return deterministic results when seeded" do
Faker.seed 123456
Faker::Code.isbn.should eq "394314441-0"
Faker::Code.isbn(13).should eq "205982563728-9"
end
end

29
src/faker/code.cr Normal file
View File

@ -0,0 +1,29 @@
module Faker
class Code < Base
def self.isbn(base : Int32 = 10)
case base
when 10 then generate_base10_isbn
when 13 then generate_base13_isbn
else raise ArgumentError.new("base must be 10 or 13")
end
end
private def self.generate_base10_isbn
values = Faker.regexify(/\d{9}/)
remainder = sum(values) { |value, index| (index + 1) * value.to_i } % 11
values += "-#{remainder == 10 ? 'X' : remainder}"
end
private def self.generate_base13_isbn
values = Faker.regexify(/\d{12}/)
remainder = sum(values) { |value, index| index.even? ? value.to_i : value.to_i * 3 } % 10
values += "-#{(10 - remainder) % 10}"
end
private def self.sum(values)
values.split(//).each_with_index.reduce(0) do |sum, (value, index)|
sum + yield(value, index)
end
end
end
end