fix EAN-13 checksum calculation, add unit tests
parent
35fd9c903d
commit
bf94b41c53
|
@ -9,11 +9,12 @@ export class EANService {
|
|||
let sum = id
|
||||
.split('')
|
||||
.map((d) => parseInt(d, 10))
|
||||
.reduce((s, d, i) => s + d * (i % 2 === 0 ? 3 : 1), 10);
|
||||
.map((d, i) => d * (i % 2 === 0 ? 1 : 3))
|
||||
.reduce((s, d) => s + d, 0);
|
||||
while (sum >= 10) {
|
||||
sum -= 10;
|
||||
}
|
||||
return sum;
|
||||
return 10 - sum;
|
||||
}
|
||||
|
||||
isValid(ean: string) {
|
||||
|
@ -28,6 +29,7 @@ export class EANService {
|
|||
if (!this.isValid(ean)) {
|
||||
throw new Error(`Invalid EAN: "${ean}"`);
|
||||
}
|
||||
return ean.slice(0, 12);
|
||||
}
|
||||
|
||||
fromID(id: string) {
|
||||
|
|
|
@ -0,0 +1,9 @@
|
|||
import { EANService } from './ean.service';
|
||||
|
||||
describe('EANService', () => {
|
||||
const eans = new EANService();
|
||||
test('generates valid EAN-13 checksum', () => {
|
||||
const sum = eans.calcChecksum('400638133393');
|
||||
expect(sum).toBe(1);
|
||||
});
|
||||
});
|
Loading…
Reference in New Issue