-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
41 lines (31 loc) · 1.24 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
const pattern = /^\d{6}-?\d{5}$/;
const firstCheckDigitMultipliers = [3, 7, 6, 1, 8, 9, 4, 5, 2, 1];
const secondCheckDigitMultipliers = [5, 4, 3, 2, 7, 6, 5, 4, 3, 2, 1];
const hasCorrectPattern = (input: string) => pattern.test(input);
const hasCorrectChecksum = (input: string, multipliers: number[]) => {
const multiplicands = input.split('').map(Number);
const sum = multipliers
.map((x, i) => x * multiplicands[i])
.reduce((x, y) => x + y);
return sum % 11 === 0;
}
const hasValidDate = (input: string) => {
let [_, dayStr, monthStr, yearStr] = /^(\d{2})(\d{2})(\d{2})/.exec(input);
const year = Number(yearStr);
const month = Number(monthStr) - 1;
const day = Number(dayStr);
const date = new Date(year, month, day);
const yearIsValid = String(date.getFullYear()).substr(-2) === yearStr;
const monthIsValid = date.getMonth() === month;
const dayIsValid = date.getDate() === day;
return yearIsValid && monthIsValid && dayIsValid;
}
export const isValid = (input: string) => {
const cleaned = input.replace(/\D/g, '');
return (
hasCorrectPattern(input) &&
hasCorrectChecksum(cleaned, firstCheckDigitMultipliers) &&
hasCorrectChecksum(cleaned, secondCheckDigitMultipliers) &&
hasValidDate(cleaned)
);
}