Skip to content

Instantly share code, notes, and snippets.

@gacardinal
Created December 5, 2020 01:25
Show Gist options
  • Save gacardinal/1a3484f1a577ccfb1a6c1265f03df22e to your computer and use it in GitHub Desktop.
Save gacardinal/1a3484f1a577ccfb1a6c1265f03df22e to your computer and use it in GitHub Desktop.
Advent of Code 2020 Day 4 Chapter 1
import { readFileSync } from 'fs';
import * as jf from 'joiful';
class Passport {
@jf.string().required()
public byr = '';
@jf.string().required()
public iyr = '';
@jf.string().required()
public eyr = '';
@jf.string().required()
public hgt = '';
@jf.string().required()
public hcl = '';
@jf.string().required()
public ecl = '';
@jf.string().required()
public pid = '';
@jf.string().optional()
public cid = '';
}
const isPassportValid = async (passport: any) => {
try {
await jf.validateAsClass(passport, Passport);
// console.log(passport, true);
return true;
} catch (e) {
// console.log(passport, false);
return false;
}
};
(async () => {
const passports = readFileSync('input.txt').toString('utf8').split('\n\n');
const parsePassport = (str: string) => {
const obj: { [key: string]: string } = {};
const kvs = str.split('\n')
.flatMap(line => line.split(' '))
.filter(x => x)
.map(kv => {
return kv.split(':')
});
kvs.forEach(kv => {
obj[kv[0]] = kv[1];
});
return obj;
};
const promises = passports.map(p => parsePassport(p)).map(async parsed => await isPassportValid(parsed));
Promise.all(promises)
.then(val => console.log(val.filter(x => x).length));
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment