Published
Edited
Dec 4, 2020
Insert cell
Insert cell
countPassportsWithAllFields(input)(fields) // part 1
Insert cell
countValidPassports(input)(validators) // part 2
Insert cell
countPassportsWithAllFields = data => requiredWords =>
removeNonemptyNewlines(data) // remaining newlines are passport boundaries
.split("\n") // array of passports
.reduce((acc, inc) => inc.match(wordsRequiredSingleRegex(requiredWords)) ? acc + 1 : acc, 0)
Insert cell
countValidPassports = data => validators =>
removeNonemptyNewlines(data) // remaining newlines are passport boundaries
.split("\n") // array of passports
.filter(all(validators)) // only passports that pass all validator functions
.length
Insert cell
// [(a -> bool)] -> a -> Bool
// for a set of functions, does a value return true for all?
all = arr => x => arr.reduce((acc, inc) => inc(x) && acc, true)
Insert cell
// Array of functions
validators = [validBirthYear, validIssueYear, validExpirationYear, validHeight, validHairColor, validEyeColor, validPID]
Insert cell
wordsRequiredSingleRegex = arr =>
new RegExp(
"^".concat(
arr
.map(word => `(?=.*${word})`)
.reduce((acc, inc) => acc.concat(inc), ""))
.concat(".*$"),
"g")
Insert cell
fields = ["byr","iyr","eyr","hgt","hcl","ecl","pid"]
Insert cell
validBirthYear = str => {
const year = +str.match(/(?<=byr:)\d+/g)
return year >= 1920 && year <= 2002
}
Insert cell
validIssueYear = str => {
const year = +str.match(/(?<=iyr:)\d+/g)
return year >= 2010 && year <= 2020
}
Insert cell
validExpirationYear = str => {
const year = +str.match(/(?<=eyr:)\d+/g)
return year >= 2020 && year <= 2030
}
Insert cell
validHeight = str => {
const height = str.match(/(?<=hgt:)\d+(cm|in)/g)
if(!height) return false
const value = +str.match(/(?<=hgt:)\d+/g)
const unit = str.match(/(?<=hgt:\d+)(cm|in)/g)
if(unit=="cm") return value >= 150 && value <= 193
return value >= 59 && value <= 76
}
Insert cell
validHairColor = str => {
const color = str.match(/(?<=hcl:)#[a-f0-9]{6}/g)
return color ? true : false
}
Insert cell
validEyeColor = str => {
const color = str.match(/(?<=ecl:)[a-z]+/g)
return color ? ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"].includes(color[0]) : false
}
Insert cell
validPID = str => {
return str.match(/(?<=pid:)\d{9}\s/g) ? true : false
}
Insert cell
removeNonemptyNewlines = x => x.replace(/(?<=.)\n/g, " ")
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more