Skip to content

Instantly share code, notes, and snippets.

@rileyjshaw
Created February 11, 2015 06:23
Show Gist options
  • Save rileyjshaw/4ce69da1511158bad0ba to your computer and use it in GitHub Desktop.
Save rileyjshaw/4ce69da1511158bad0ba to your computer and use it in GitHub Desktop.
Validate a Canadian Social Insurance Number (SIN)
/**
* 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.';
}
@3r1k0n
Copy link

3r1k0n commented Jul 14, 2020

thank you!

@barsl
Copy link

barsl commented Jan 27, 2021

Thank you very much, this is helpful

@rveldpaus
Copy link

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