You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
14 lines
502 B
TypeScript
14 lines
502 B
TypeScript
/** EAN-13 check digit: weights alternate 1,3 over the first 12 digits. */
|
|
export function ean13CheckDigit(first12: string): number {
|
|
if (!/^\d{12}$/.test(first12)) throw new Error('EAN-13 body must be 12 digits')
|
|
let sum = 0
|
|
for (let i = 0; i < 12; i++) {
|
|
sum += Number(first12[i]) * (i % 2 === 0 ? 1 : 3)
|
|
}
|
|
return (10 - (sum % 10)) % 10
|
|
}
|
|
|
|
export function isValidEan13(code: string): boolean {
|
|
return /^\d{13}$/.test(code) && ean13CheckDigit(code.slice(0, 12)) === Number(code[12])
|
|
}
|