Skip to content

Instantly share code, notes, and snippets.

@Mellen
Last active December 4, 2020 12:51
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 Mellen/876c8061f83b8f0c1fd14b742dba4d4e to your computer and use it in GitHub Desktop.
Save Mellen/876c8061f83b8f0c1fd14b742dba4d4e to your computer and use it in GitHub Desktop.
function IDCheckp1()
{
const lines = document.getElementsByTagName('pre')[0].innerHTML.split('\n');
const minFields = ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'];
let fields = [];
const validCount = lines.reduce((count, line) =>
{
if(line.trim() === '')
{
if(minFields.every(field => fields.indexOf(field) > -1))
{
count++;
}
fields = [];
}
else
{
fields = fields.concat(line.split(' ')
.map(kvp => kvp.split(':')[0]));
}
return count;
},0);
return validCount;
}
function IDCheckp2()
{
const lines = document.getElementsByTagName('pre')[0].innerHTML.split('\n');
const minFields = ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'];
let fields = [];
let parts = [];
const validCount = lines.reduce((count, line) =>
{
if(line.trim() === '')
{
if(minFields.every(field => fields.indexOf(field) > -1))
{
let ID = JSON.parse('{'+parts.join(',')+'}');
if(isValidID(ID))
{
count++;
}
}
fields = [];
parts = [];
}
else
{
fields = fields.concat(line.split(' ')
.map(kvp => kvp.split(':')[0]));
parts = parts.concat(line.split(' ')
.map(kvp =>
{
let [key, value] = kvp.split(':');
return `"${key}":"${value}"`;
}));
}
return count;
},0);
function isValidID(ID)
{
return (
ID['byr'].match(/^(19[2-9]\d|200[012])$/)
&& ID['iyr'].match(/^20(1\d|20)$/)
&& ID['eyr'].match(/^20(2\d|30)$/)
&& isValidHeight(ID['hgt'])
&& ID['hcl'].match(/^#[0-9a-fA-F]{6}$/)
&& ['amb','blu','brn','gry','grn','hzl','oth'].includes(ID['ecl'])
&& ID['pid'].match(/^\d{9}$/)
);
}
function isValidHeight(heightstr)
{
let heightparts = heightstr.match(/^(\d+)(cm|in)$/);
if(heightparts)
{
let height = parseInt(heightparts[1], 10);
if(heightparts[2] == 'cm')
{
return Math.min(Math.max(height, 150), 193) == height;
}
else if(heightparts[2] == 'in')
{
return Math.min(Math.max(height, 59), 76) == height;
}
}
return false;
}
return validCount;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment