Last active
June 29, 2021 00:11
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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