Created
September 24, 2018 04:31
-
-
Save this-is-richard/23886ff3df7627701fafb515008629d4 to your computer and use it in GitHub Desktop.
hkid-validation.js
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
function charToNumber(char) { | |
if (char === ' ') { | |
return 58 | |
} else if (!isNaN(char)) { | |
return parseInt(char) | |
} else { | |
return char.toUpperCase().charCodeAt(0) - 55; | |
} | |
} | |
function hkidValidator(input) { | |
if(!input) return false; | |
if(typeof input !== 'string') return false; | |
const inputLength = input.length; | |
if (inputLength < 8 || inputLength > 9) return false; | |
let hkid = input; | |
if (inputLength === 8) { | |
hkid = ' ' + hkid; | |
} | |
console.assert(hkid.length === 9); | |
const lastChar = hkid[hkid.length - 1]; | |
if (charToNumber(lastChar) >= 11) return false; | |
let total = hkid.split('') | |
.map(c => charToNumber(c)) | |
.reduce((acc, curr, i) => acc + (hkid.length - i) * curr, 0); | |
if(total % 11 !== 0) return false; | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment