Skip to content

Instantly share code, notes, and snippets.

@slykar
Created August 9, 2019 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slykar/5844890ec7d13ef9c08d175915ef36f2 to your computer and use it in GitHub Desktop.
Save slykar/5844890ec7d13ef9c08d175915ef36f2 to your computer and use it in GitHub Desktop.
// See https://pl.wikipedia.org/wiki/PESEL#Data_urodzenia
// See https://en.wikipedia.org/wiki/PESEL#Birthdates
const CENTURY_MAP: {[k: number]: number} = {
0: 1900,
1: 2000,
2: 2100,
3: 2200,
4: 1800,
};
export function isValid(pesel: string): boolean {
if (pesel.length !== 11) {
return false;
}
const digits: number[] = pesel.split('').map(Number);
const checkWeights = [9, 7, 3, 1, 9, 7, 3, 1, 9, 7];
const checkSum = checkWeights.reduce((sum, weight, idx) => {
return sum + weight * digits[idx];
}, 0);
return checkSum % 10 === digits.pop();
}
export function getGender(pesel: string): 'f' | 'm' {
const genderComponent = Number(pesel[9]);
return genderComponent % 2 === 0 ? 'f' : 'm';
}
export function getBirthDate(pesel: string): Date {
const yearComponent: number = Number(pesel.slice(0, 2));
const monthComponent: number = Number(pesel.slice(2, 4));
const day: number = Number(pesel.slice(4, 6));
const century: number = CENTURY_MAP[Math.floor(monthComponent / 20)];
const year = century + yearComponent;
const month = monthComponent % 20;
return new Date(`${year}-${month}-${day}`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment