-
Notifications
You must be signed in to change notification settings - Fork 0
/
4.ts
88 lines (69 loc) · 2.22 KB
/
4.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import path from "path";
import fs, { access, link } from "fs";
import readline from "readline";
const data = fs.openSync(path.resolve("4.txt"), "r");
const reader = readline.createInterface({
input: fs.createReadStream(path.resolve("4.txt"))
})
let current: string[] = [];
let count = 0;
reader.on("line", data => {
if (data === "") {
if (verify(current)) {
count++;
}
current = []
} else {
current = current.concat(data.split(/\s/));
}
})
reader.on("close", () => {
console.log("result", count);
})
const mandatoryFields = {
byr: (v: string) => parseInt(v, 10) >= 1920 && parseInt(v, 10) <= 2002,
iyr: (v: string) => parseInt(v, 10) >= 2010 && parseInt(v, 10) <= 2020,
eyr: (v: string) => parseInt(v, 10) >= 2020 && parseInt(v, 10) <= 2030,
hgt: (v: string) => {
const matches = v.match(/(\d{1,3})(cm|in)$/)
if (!matches) {
return false;
}
const value = parseInt(matches[1], 10);
if (matches[2] === "cm") {
console.log("height in cm", value);
return value >= 150 && value <=193
}
if (matches[2] === "in") {
console.log("height in in", value);
return value >= 59 && value <=76
}
return false;
},
hcl: (v: string) => v.match(/#[a-fA-F0-9]{6}$/),
ecl: (v: string) => v.match(/amb|blu|brn|gry|grn|hzl|oth$/),
pid: (v: string) => v.match(/\d{9}$/),
}
const verify = (passportTokens: string[]) => {
const fields = passportTokens.reduce((acc, c) => {
const [f, v] = c.split(":");
return {...acc, [f]: v}
}, {});
console.log("pf", fields)
if (!Object.keys(mandatoryFields).every(f => Object.keys(fields).includes(f))) {
return false;
}
for (const fieldName in fields) {
const fieldValue = fields[fieldName as keyof typeof fields];
const rule = mandatoryFields[fieldName as keyof typeof mandatoryFields];
console.log(`checking rule for ${fieldName} with value: ${fieldValue}`)
if (fieldName === "cid") {
continue;
}
if (!rule(fieldValue)) {
return false;
}
}
console.log("valid");
return true;
}