UNPKG

swedish-ssn-tool

Version:

Small utility for validating and generating Swedish social security number.

3 lines (2 loc) 1.64 kB
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).SwedishSSN=e()}(this,(function(){"use strict";const t=Object.freeze({MALE:"male",FEMALE:"female"});function e(t){try{return t.toLocaleDateString("sv-SE",{year:"2-digit",month:"2-digit",day:"2-digit"}).replace(/\D/g,"")}catch(t){throw new Error("Invalid date format")}}function n(e,n,a){const i=Math.floor(Math.random()*(n-e+1)+e);let c=i;switch(a){case t.MALE:c=r(i)?i+1:i;break;case t.FEMALE:c=o(i)?i+1:i}return c.toString().substring(1)}const r=t=>t%2==0,o=t=>!r(t);const a=(t,e)=>t.flatMap(e);function i(t){const e=[2,1,2,1,2,1,2,1,2],n=t.map(((t,n)=>t*e[n])),r=a(n,(t=>{return t>=10?[(e=t,Math.floor(e%10)+Math.floor(e/10))]:[t];var e})).reduce(((t,e)=>t+e),0);return Math.floor(9*r%10)}function c(t){return`${t.slice(0,6).join("")}-${t.slice(6,10).join("")}`}function s(t){const e=t.replace(/\D/g,"").split("").map(Number);return 12===e.length?e.slice(2,12):e}return class{static validate(t){if(null==t||""===t)return!1;const e=s(t);if(10!==e.length)return!1;const n=e.pop();return i(e)===n}static generateRandomSSN(){const t=function(){const t=new Date(1900,0,1).getTime(),e=new Date(2099,11,31).getTime();return new Date(t+Math.random()*(e-t))}(),r=n(1e3,9998,"random"),o=s(e(t)+r),a=i(o);return o.push(a),c(o)}static generateSSNWithParameters(t,r){if(!(t instanceof Date)||isNaN(t))throw new Error("Invalid birthdate provided");const o=n(1e3,9999,r),a=s(e(t)+o),u=i(a);return a.push(u),c(a)}}})); //# sourceMappingURL=swedish-ssn.min.js.map