Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ Change log itself follows [Keep a CHANGELOG](http://keepachangelog.com) format.
- `Faker.Currency.code/0` remove duplicates/replace old currencies [[@yassinrais](https://github.com/yassinrais)]
- `Faker.Adress.PtBr` - fix model documentation [[@laraujo7](https://github.com/laraujo7)]
- `Faker.Address.En/0` corrected formatting for US and Britian [[@atavistock](https://github.com/atavistock)]
- `Faker.Vehicle.En` - ensure generated VINs have the correct check digit [[@rubysolo](https://github.com/rubysolo)]

### Security

Expand Down
59 changes: 53 additions & 6 deletions lib/faker/vehicle.ex
Original file line number Diff line number Diff line change
Expand Up @@ -244,20 +244,21 @@ defmodule Faker.Vehicle do
localize(:transmission)

@doc """
Returns a vehicle identification number string
Returns a vehicle identification number string with the correct check digit

## Examples
iex> Faker.Vehicle.vin()
"1C68203VCV0360337"
"1C68203V9V0360337"
iex> Faker.Vehicle.vin()
"5190V7FL8YX113016"
"5190V7FL3YX113016"
iex> Faker.Vehicle.vin()
"4RSE9035H9JA97940"
"4RSE903569JA97940"
iex> Faker.Vehicle.vin()
"59E4A13G890C97377"
"59E4A13G190C97377"
"""
def vin do
Util.format("%10x%y%x%5d",
"%10x%y%x%5d"
|> Util.format(
x: fn ->
Util.pick([Util.upper_letter(), "#{Util.digit()}"], ["I", "O", "Q"])
end,
Expand All @@ -268,5 +269,51 @@ defmodule Faker.Vehicle do
"#{Util.digit()}"
end
)
|> set_check_digit()
end

@position_weights [8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2]
@character_values %{
"A" => 1,
"B" => 2,
"C" => 3,
"D" => 4,
"E" => 5,
"F" => 6,
"G" => 7,
"H" => 8,
"J" => 1,
"K" => 2,
"L" => 3,
"M" => 4,
"N" => 5,
"P" => 7,
"R" => 9,
"S" => 2,
"T" => 3,
"U" => 4,
"V" => 5,
"W" => 6,
"X" => 7,
"Y" => 8,
"Z" => 9
}

defp set_check_digit(partial_vin) do
checksum =
partial_vin
|> String.graphemes()
|> Enum.with_index()
|> Enum.reduce(0, fn {character, position}, sum ->
weight = Enum.at(@position_weights, position)
value = Map.get_lazy(@character_values, character, fn -> String.to_integer(character) end)

sum + weight * value
end)
|> rem(11)

check_digit = if checksum > 9, do: "X", else: to_string(checksum)

String.slice(partial_vin, 0..7) <> check_digit <> String.slice(partial_vin, 9..-1)
end
end