Created
February 11, 2015 06:23
-
-
Save rileyjshaw/4ce69da1511158bad0ba to your computer and use it in GitHub Desktop.
Validate a Canadian Social Insurance Number (SIN)
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
/** | |
* Validate a Canadian Social Insurance Number (SIN) | |
* @param {num || str} sin A 9-digit Canadian SIN | |
* @return {bool} Validity of the input SIN | |
*/ | |
function validateSIN (sin) { | |
var check, even, tot; | |
if (typeof sin === 'number') { | |
sin = sin.toString(); | |
} | |
if (sin.length === 9) { | |
// convert to an array & pop off the check digit | |
sin = sin.split(''); | |
check = +sin.pop(); | |
even = sin | |
// take the digits at the even indices | |
.filter(function (_, i) { return i % 2; }) | |
// multiply them by two | |
.map(function (n) { return n * 2; }) | |
// and split them into individual digits | |
.join('').split(''); | |
tot = sin | |
// take the digits at the odd indices | |
.filter(function (_, i) { return !(i % 2); }) | |
// concatenate them with the transformed numbers above | |
.concat(even) | |
// it's currently an array of strings; we want numbers | |
.map(function (n) { return +n; }) | |
// and take the sum | |
.reduce(function (acc, cur) { return acc + cur; }); | |
// compare the result against the check digit | |
return check === (10 - (tot % 10)) % 10; | |
} else throw sin + ' is not a valid sin number.'; | |
} |
Thank you very much, this is helpful
Apparently this is known as the Luhn algorithm
Another implementation of the check
/**
* Validate a Canadian Social Insurance Number (SIN)
* @param {num || str} sin A 9-digit Canadian SIN
* @return {bool} Validity of the input SIN
*/
function validateSIN (sin) {
let multiplyEveryOtherBy2 = (val, index) => val *((index%2)+1) ;
let sumValues = (acc,val)=>acc+parseInt(val);
if (typeof sin === 'number') {
sin = sin.toString();
}
if (sin.length !== 9) {
console.log("Wrong length");
return false;
}
// convert to an array & pop off the check digit
sin = sin.split('');
const check = parseInt(sin.pop());
const sum = sin
.map(multiplyEveryOtherBy2)
//To individual digits
.join('').split('')
.reduce(sumValues,0)
* 9 % 10
return check === sum;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thank you!