isikukood
Version:
Estonian personal ID (isikukood) JavaScript module
4 lines (3 loc) • 2.48 kB
JavaScript
;// isikukood.esm.js, https://github.com/dknight/Isikukood-js
class l{constructor(t){this._code=String(t)}get code(){return this._code}set code(t){this._code=String(t)}getControlNumber(t=""){t||(t=this.code);const r=[1,2,3,4,5,6,7,8,9,1],s=[3,4,5,6,7,8,9,1,2,3];let o=0,n=0;for(let e=0;e<10;++e)n+=Number(t.charAt(e))*r[e];if(o=n%11,n=0,o===10){for(let e=0;e<10;++e)n+=Number(t.charAt(e))*s[e];o=n%11,o===10&&(o=0)}return o}validate(){if(this.code.charAt(0)==="0"||this.code.length!==11||this.getControlNumber()!==Number(this.code.charAt(10)))return!1;const r=Number(this.code.substring(1,3)),s=Number(this.code.substring(3,5)),o=Number(this.code.substring(5,7)),n=this.getBirthday();return r===n.getFullYear()%100&&n.getMonth()+1===s&&o===n.getDate()}getGender(){const t=this.code.charAt(0);let r;switch(t){case"1":case"3":case"5":r=a.MALE;break;case"2":case"4":case"6":r=a.FEMALE;break;default:r=a.UNKNOWN}return r}getAge(){return Math.floor((Date.now()-this.getBirthday().getTime())/(86400*1e3)/365.25)}getBirthday(){let t=Number(this.code.substring(1,3));const r=Number(this.code.substring(3,5).replace(/^0/,""))-1,s=Number(this.code.substring(5,7).replace(/^0/,"")),o=this.code.charAt(0);for(let n=1,e=1800;n<=8;n+=2,e+=100)[n,n+1].map(String).includes(o)&&(t+=e);return new Date(t,r,s)}parse(){return l.parse(this.code)}static parse(t){const r=new this(t);return{gender:r.getGender(),birthDay:r.getBirthday(),age:r.getAge()}}static generate(t={}){let r,s,o;const n=t.gender||(Math.round(Math.random())===0?a.MALE:a.FEMALE);let e="";const u=["00","01","02","22","27","37","42","47","49","52","57","60","65","70","95"];if(![a.MALE,a.FEMALE].includes(n))return"";if(t.birthYear?r=t.birthYear:r=Math.round(Math.random()*100+1900+(new Date().getFullYear()-2e3)),t.birthMonth?s=t.birthMonth:s=Math.floor(Math.random()*12)+1,t.birthDay)o=t.birthDay;else{const i=new Date(r,s,0).getDate();o=Math.floor(Math.random()*i)+1}for(let i=1800,c=2;i<=2100;i+=100,c+=2)if(r>=i&&r<i+100)switch(n){case a.MALE:e+=String(c-1);break;case a.FEMALE:e+=String(c);break;default:return""}return e+=String(r).substring(2,4),e+=String(s).length===1?`0${s}`:`${s}`,e+=String(o).length===1?`0${o}`:`${o}`,e+=u[Math.floor(Math.random()*u.length)],e+=String(Math.floor(Math.random()*10)),e+=String(this.prototype.getControlNumber(e)),e}}var a=(h=>(h.MALE="male",h.FEMALE="female",h.UNKNOWN="unknown",h))(a||{});export{a as Gender,l as default};
//# sourceMappingURL=isikukood.esm.min.js.map