verhoeff-algorithm
Version:
A TypeScript implementation of the Verhoeff algorithm.
50 lines (44 loc) • 1.51 kB
text/typescript
const multiplicationTable: number[][] = [
[],
[],
[],
[],
[],
[],
[],
[],
[],
[]
];
const permutationTable: number[][] = [
[],
[],
[],
[],
[],
[],
[],
[]
];
/**
* Calculates the Verhoeff checksum for a given number array.
* @param numberArray An array of digits representing the number.
* @returns The checksum value.
*/
function calculateChecksum(numberArray: number[]): number {
let c = 0;
const invertedArray = numberArray.slice().reverse();
invertedArray.forEach((val, i) => {
c = multiplicationTable[c][permutationTable[i % 8][val]];
});
return c;
}
/**
* Validates if the given number passes the Verhoeff check.
* @param number A string representing the number to check.
* @returns A boolean indicating if the number is valid.
*/
export function isValidVerhoeff(number: string): boolean {
const numberArray: number[] = number.split("").map(Number);
return calculateChecksum(numberArray) === 0;
}