Created
February 24, 2017 09:26
-
-
Save nikhil-bhandari/02bc6e092264483a0601f2f38ecee37b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| // Code to validate swedish person number | |
| // Based on logic on wikipedia | |
| // https://en.wikipedia.org/wiki/Personal_identity_number_(Sweden)#Checksum | |
| function validate(number) { | |
| var personNumber = removeNonNumericChars(number); | |
| if (personNumber.length != 10 && personNumber.length != 12) { | |
| return console.log("Asa") && false; | |
| } | |
| var digits = personNumber.split(""); | |
| var checksum = digits.pop(); | |
| var sumOf9Digits = digits | |
| .map(function (item, index) { | |
| var result; | |
| if (index % 2 == 0) { | |
| result = singleDigiSum(item * 2); | |
| } else { | |
| result = singleDigiSum(item); | |
| } | |
| return result; | |
| }) | |
| .reduce(sum, 0); | |
| var lastDigitOfSum = sumOf9Digits % 10; | |
| return checksum == (10 - lastDigitOfSum); | |
| } | |
| function removeNonNumericChars(number){ | |
| return number.toString().replace(/\D/g,''); | |
| } | |
| function sumOfDigits(number) { | |
| return number | |
| .toString() | |
| .split('') | |
| .map(Number) | |
| .reduce(sum, 0); | |
| } | |
| function singleDigiSum(num) { | |
| while (numDigits(num) != 1) { | |
| num = sumOfDigits(num) | |
| } | |
| return num; | |
| } | |
| function numDigits(x) { | |
| return Math.max(Math.floor(Math.log10(Math.abs(x))), 0) + 1; | |
| } | |
| function sum(a, b) { | |
| return +a + (+b); | |
| } | |
| validate("8112289874"); | |
| validate("1602079954"); | |
| validate("1001018702"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just too bloody awesome