cdigit
Version:
Collection of check digit algorithms implemented in JavaScript
80 lines (67 loc) • 2.21 kB
text/typescript
/**
* cdigit
*
* @copyright 2018-2021 LiosK
* @license (MIT OR Apache-2.0)
*/
import { Algo, helper } from "./common";
/**
* Verhoeff algorithm implementation
*
* Note: There is not a firm consensus on the direction (left to right or right
* to left) in which a Verhoeff calculator scans numeric text to construct an
* input digit sequence. This implementation is hard coded to read a string from
* right to left and append the check digit at the rightmost position, which is
* a consistent behavior with other popular implementations. Reverse the input
* string before calling this class' methods if you need to interpret a string
* from left to right.
*/
class Verhoeff implements Algo {
name = "verhoeff";
longName = "Verhoeff Algorithm";
/** Verhoeff multiplication table */
private d = [
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
];
/** Verhoeff permutation table */
private p = [
[],
[],
[],
[],
[],
[],
[],
[],
];
/** Verhoeff inverse table */
private inv = ["0", "4", "3", "2", "1", "5", "6", "7", "8", "9"];
compute(num: string): string {
const ds = `${String(num).replace(/[^0-9]/g, "")}0`;
let c = 0;
for (let i = 0, len = ds.length; i < len; i += 1) {
c = this.d[c][this.p[i & 7][Number(ds[len - i - 1])]];
}
return this.inv[c];
}
generate(num: string): string {
return `${num}${this.compute(num)}`;
}
validate(num: string): boolean {
const [src, cc] = this.parse(num);
return this.compute(src) === cc;
}
parse(num: string): [string, string] {
return helper.parseTail(num, 1);
}
}
export const verhoeff = new Verhoeff();