metropolis/src/items/ean/ean.service.ts

40 lines
916 B
TypeScript
Raw Normal View History

2021-07-21 00:54:19 +02:00
import { Controller } from '@nestjs/common';
import assert from 'assert';
@Controller()
export class EANService {
// https://en.wikipedia.org/wiki/International_Article_Number#Calculation_of_checksum_digit
calcChecksum(id: string) {
assert(id.length === 12);
let sum = id
.split('')
.map((d) => parseInt(d, 10))
.map((d, i) => d * (i % 2 === 0 ? 1 : 3))
.reduce((s, d) => s + d, 0);
while (sum > 10) {
2021-07-21 00:54:19 +02:00
sum -= 10;
}
return 10 - sum;
2021-07-21 00:54:19 +02:00
}
isValid(ean: string) {
return this.calcChecksum(ean.slice(0, 12)) === parseInt(ean[12], 10);
}
toID(ean: string) {
2021-07-21 01:14:20 +02:00
if (ean.length === 12) {
// it already is an ID
return ean;
}
2021-07-21 00:54:19 +02:00
if (!this.isValid(ean)) {
throw new Error(`Invalid EAN: "${ean}"`);
}
return ean.slice(0, 12);
2021-07-21 00:54:19 +02:00
}
fromID(id: string) {
assert(id.length === 12);
return id + this.calcChecksum(id);
}
}