Skip to content

Instantly share code, notes, and snippets.

@markusand
Last active June 29, 2021 00:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markusand/26daffac64fe44a185c5436fc05f6e9b to your computer and use it in GitHub Desktop.
Save markusand/26daffac64fe44a185c5436fc05f6e9b to your computer and use it in GitHub Desktop.
Use function to generate and validate Luhn mod N algorithm checksums for strings
export default (chars = 'ABCDEFGHJKMNPQRSTUVWXYZ0123456789') => {
const checksum = input => {
const { sum } = input.split('').reverse().reduce((acc, char) => {
const addend = acc.factor * chars.indexOf(char);
acc.factor = acc.factor === 2 ? 1 : 2;
acc.sum += Math.floor(addend / chars.length) + (addend % chars.length);
return acc;
}, { sum: 0, factor: 2 });
const remainder = sum % chars.length;
return chars[(chars.length - remainder) % chars.length];
};
const generate = input => `${input}${checksum(input)}`;
const validate = input => input.slice(-1) === checksum(input.slice(0, -1));
return { generate, validate };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment