Skip to content

Instantly share code, notes, and snippets.

@kirill578
Created January 4, 2022 20:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kirill578/0f92d23065c11cd520e11a2cac8dbf1f to your computer and use it in GitHub Desktop.
Save kirill578/0f92d23065c11cd520e11a2cac8dbf1f to your computer and use it in GitHub Desktop.
export const luhn = (value: string) => {
let nCheck = 0;
let nDigit = 0;
let bEven = true;
const newValue = value.replace(/D/g, '');
for (let n = newValue.length - 1; n >= 0; n -= 1) {
const cDigit = newValue.charAt(n);
nDigit = parseInt(cDigit, 10);
if (bEven) {
nDigit *= 2;
if (nDigit > 9) {
nDigit -= 9;
}
}
nCheck += nDigit;
bEven = !bEven;
}
return (1000 - nCheck) % 10;
};
export const verifyBarcode = (barcode: string) => {
const originalCode = barcode.slice(1, -2);
const raw = `A${originalCode}${luhn(originalCode)}${luhn(
(parseInt(originalCode, 10) + 1).toString()
)}`;
return raw === barcode;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment