1
0
mirror of https://github.com/askn/faker.git synced 2023-08-10 21:13:01 +03:00

Added Faker::Code.imei

This commit is contained in:
Egor Romanov 2022-02-16 22:46:05 +03:00
parent e2c95c114d
commit 7f32a1197b
3 changed files with 45 additions and 1 deletions

View File

@ -83,7 +83,9 @@ Faker::Business.credit_card_type #=> "visa"
```crystal ```crystal
Faker::Code.isbn #=> 640354399-7 Faker::Code.isbn #=> "640354399-7"
Faker::Code.imei #=> "531691246033652"
``` ```

View File

@ -9,9 +9,14 @@ describe Faker::Code do
Faker::Code.isbn(13).match(/^\d{12}-\d$/).should_not eq nil Faker::Code.isbn(13).match(/^\d{12}-\d$/).should_not eq nil
end end
it "imei" do
Faker::Code.imei.match(/\A[\d.:\-\s]+\z/i).should_not eq nil
end
it "should return deterministic results when seeded" do it "should return deterministic results when seeded" do
Faker.seed 123456 Faker.seed 123456
Faker::Code.isbn.should eq "394314441-0" Faker::Code.isbn.should eq "394314441-0"
Faker::Code.isbn(13).should eq "205982563728-9" Faker::Code.isbn(13).should eq "205982563728-9"
Faker::Code.imei.should eq "860839366575918"
end end
end end

View File

@ -1,5 +1,7 @@
module Faker module Faker
class Code < Base class Code < Base
RBI = %w[01 10 30 33 35 44 45 49 50 51 52 53 54 86 91 98 99]
def self.isbn(base : Int32 = 10) def self.isbn(base : Int32 = 10)
case base case base
when 10 then generate_base10_isbn when 10 then generate_base10_isbn
@ -8,6 +10,41 @@ module Faker
end end
end end
def self.imei
str = Array.new(15, 0)
sum = 0
len = 15
# Fill in the first two values of the string based with the specified prefix.
arr = RBI.sample(Faker.rng)
str[0] = arr[0].to_i
str[1] = arr[1].to_i
pos = 2
# Fill all the remaining numbers except for the last one with random values.
while pos < (len - 1)
str[pos] = Faker.rng.rand(0..9)
pos += 1
end
# Calculate the Luhn checksum of the values thus far
len_offset = (len + 1) % 2
(0..(len - 1)).each do |position|
if (position + len_offset).odd?
t = str[position] * 2
t -= 9 if t > 9
sum += t
else
sum += str[position]
end
end
str[len - 1] = (10 - (sum % 10)) % 10
str.join("")
end
private def self.generate_base10_isbn private def self.generate_base10_isbn
values = Faker.regexify(/\d{9}/) values = Faker.regexify(/\d{9}/)
remainder = sum(values) { |value, index| (index + 1) * value.to_i } % 11 remainder = sum(values) { |value, index| (index + 1) * value.to_i } % 11