Skip to content

Instantly share code, notes, and snippets.

@IvanAdmaers
Created June 3, 2022 09:43
Show Gist options
  • Save IvanAdmaers/488309771b85f97be28b40d0d87cb3af to your computer and use it in GitHub Desktop.
Save IvanAdmaers/488309771b85f97be28b40d0d87cb3af to your computer and use it in GitHub Desktop.
isValidVin
import isValidVin from './isValidVin.ts';
describe('isValidVin', () => {
it('should return false for an invalid 16 digit VIN', () => {
const vin = 'JHLRM4H70CC01839';
expect(isValidVin(vin)).toBe(false);
});
it('should return false for an invalid 18 digit VIN', () => {
const vin = 'JHLRM4H70CC01839AB';
expect(isValidVin(vin)).toBe(false);
});
it('should return false for an invalid 17 digit VIN with `i`', () => {
const vin = 'JHLRM4H70CC01839i';
expect(isValidVin(vin)).toBe(false);
});
it('should return false for an invalid 17 digit VIN with `I`', () => {
const vin = 'JHLRM4H70CC01839I';
expect(isValidVin(vin)).toBe(false);
});
it('should return false for an invalid 17 digit VIN with `o`', () => {
const vin = 'JHLRM4H70CC01839o';
expect(isValidVin(vin)).toBe(false);
});
it('should return false for an invalid 17 digit VIN with `O`', () => {
const vin = 'JHLRM4H70CC01839o';
expect(isValidVin(vin)).toBe(false);
});
it('should return false for an invalid 17 digit VIN with `q`', () => {
const vin = 'JHLRM4H70CC01839o';
expect(isValidVin(vin)).toBe(false);
});
it('should return false for an invalid 17 digit VIN with `Q`', () => {
const vin = 'JHLRM4H70CC01839o';
expect(isValidVin(vin)).toBe(false);
});
it('should return true for a valid 17 digit VIN in lowercase letters', () => {
const vin = 'jhlrm4h70cc018394';
expect(isValidVin(vin)).toBe(true);
});
it('should return false for an incorrect check digit with an incorrect 17 digit VIN', () => {
const vin = 'WVWUK63B82P546818';
expect(isValidVin(vin)).toBe(false);
});
it('should return true for a correct 17 digit VIN', () => {
const vin = '11111111111111111';
expect(isValidVin(vin)).toBe(true);
});
});
/**
* This function checks is a VIN valid
*/
const isValidVin = (vinCode: string): boolean => {
const vin: string = vinCode.toLowerCase();
if (!/^[a-hj-npr-z0-9]{8}[0-9xX][a-hj-npr-z0-9]{8}$/.test(vin)) {
return false;
}
const transliterationTable = {
'0': 0,
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
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,
};
const weightsTable: Array<number> = [
8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2,
];
let sum: number = 0;
for (let i = 0; i < vin.length; i += 1) {
sum +=
transliterationTable[vin.charAt(i) as keyof typeof transliterationTable] *
weightsTable[i];
}
const mod: number = sum % 11;
return mod === 10 ? vin.charAt(8) === 'x' : vin.charAt(8) === mod.toString();
};
export default isValidVin;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment