Commit 447a9c1e authored by Marcel Behrmann's avatar Marcel Behrmann

Initialize TSLint

parent 56794839
import * as program from 'commander';
import * as fs from 'fs';
import create from './src/commands/create';
import * as program from "commander";
import * as fs from "fs";
import create from "./src/commands/create";
program
.version('1.0.0')
.option('-t, --token [token]')
.option('-f, --force', 'force creation of day, WARNING: WILL OVERWRITE')
.version("1.0.0")
.option("-t, --token [token]")
.option("-f, --force", "force creation of day, WARNING: WILL OVERWRITE")
.parse(process.argv);
if (!program.args.length) {
......@@ -14,14 +14,14 @@ if (!program.args.length) {
}
if (!program.token) {
if(!fs.existsSync('.token')) {
if (!fs.existsSync(".token")) {
console.error("I can not find an active session, please update session token (-t)");
process.exit(1);
} else {
program.token = fs.readFileSync('.token', 'utf8');
program.token = fs.readFileSync(".token", "utf8");
}
} else {
fs.writeFileSync('.token', program.token);
fs.writeFileSync(".token", program.token);
}
create(program);
import * as program from 'commander';
import run from './src/commands/run';
import * as program from "commander";
import run from "./src/commands/run";
program
.version('1.0.0')
.option('-p, --partial [part]', 'only run the first part of the day')
.option('-s, --sample', 'run the sample for the day')
.option('-l, --logging', 'enable day specific logs')
.version("1.0.0")
.option("-p, --partial [part]", "only run the first part of the day")
.option("-s, --sample", "run the sample for the day")
.option("-l, --logging", "enable day specific logs")
.parse(process.argv);
if (!program.args.length) {
......
const program = require('commander');
program
.version('2018.3')
.command('run [day]', 'execute the script for a day')
.command('list', 'list the available days')
.parse(process.argv);
\ No newline at end of file
import * as child_process from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import * as child_process from "child_process";
import * as fs from "fs";
import * as path from "path";
import { leftPad } from './src/Utils';
import { leftPad } from "./src/Utils";
type part = { num: number, output: string, done: boolean, time: [number, number] };
interface IPart { num: number; output: string; done: boolean; time: [number, number]; }
const calendar: Array<{ day: String, part1: part, part2: part }> = [];
const calendar: Array<{ day: string, part1: IPart, part2: IPart }> = [];
let bin = path.resolve('node_modules', '.bin', 'ts-node');
const bin = path.resolve("node_modules", ".bin", "ts-node");
for (let i = 1; i < 26; i++) {
let day = {
day: leftPad(i.toString(), 2, '0'),
part1: {
num: 1,
const day = {
day: leftPad(i.toString(), 2, "0"),
part1: {
done: true,
num: 1,
output: null,
time: null,
done: true,
},
part2: {
done: true,
num: 2,
output: null,
time: null,
done: true,
}
},
};
let res: Buffer = null;
let time: [number, number] = null;
try {
console.log(`Running Day ${i} Part 1`);
time = process.hrtime();
res = child_process.execSync(`${bin} app-run.ts ${i} -p 1`);
day.part1.output = res.toString('utf8');
day.part1.output = res.toString("utf8");
day.part1.time = process.hrtime(time);
} catch {
day.part1.done = false;
......@@ -46,7 +46,7 @@ for (let i = 1; i < 26; i++) {
time = process.hrtime();
res = child_process.execSync(`${bin} app-run.ts ${i} -p 2`);
day.part2.output = res.toString('utf8');
day.part2.output = res.toString("utf8");
day.part2.time = process.hrtime(time);
} catch {
day.part2.done = false;
......@@ -56,4 +56,4 @@ for (let i = 1; i < 26; i++) {
calendar.push(day);
}
fs.writeFileSync('./page/data/days.json', JSON.stringify(calendar));
\ No newline at end of file
fs.writeFileSync("./page/data/days.json", JSON.stringify(calendar));
export type Input = Array<string>;
export type Output = Array<string> | string;
\ No newline at end of file
export type Input = string[];
export type Output = string[] | string;
import axios, { AxiosInstance } from 'axios';
import * as fs from 'fs';
import { SSL_OP_NETSCAPE_CHALLENGE_BUG } from 'constants';
import axios, { AxiosInstance } from "axios";
import { SSL_OP_NETSCAPE_CHALLENGE_BUG } from "constants";
import * as fs from "fs";
export default class Client {
private client: AxiosInstance = null;
constructor(token: string) {
this.client = axios.create({
baseURL: 'https://adventofcode.com/2018',
headers: { 'Cookie' : `session=${token}` }
});
baseURL: "https://adventofcode.com/2018",
headers: { Cookie : `session=${token}` },
});
}
public async getInputForDay(num: number): Promise<string> {
let data = '';
let data = "";
try {
data = this.getFromCache(num);
if (data === null) {
const response = await this.client.get(`/day/${num}/input`);
data = response.data;
......@@ -25,25 +25,24 @@ export default class Client {
}
return data;
} catch(error) {
console.log(error);
} catch (error) {
return null;
}
}
private setCache(num: number, data:string) {
if (!fs.existsSync('.cache')) {
fs.mkdirSync('.cache');
private setCache(num: number, data: string) {
if (!fs.existsSync(".cache")) {
fs.mkdirSync(".cache");
}
fs.writeFileSync(`.cache/${num}`, data, {encoding: 'utf8'});
fs.writeFileSync(`.cache/${num}`, data, {encoding: "utf8"});
}
private getFromCache(num: number): string {
if (fs.existsSync('.cache') && fs.existsSync(`.cache/${num}`)) {
return fs.readFileSync(`.cache/${num}`, 'utf8');
if (fs.existsSync(".cache") && fs.existsSync(`.cache/${num}`)) {
return fs.readFileSync(`.cache/${num}`, "utf8");
}
return null;
}
}
\ No newline at end of file
}
import InputFile from "./io/InputFile";
import InputParser from "./io/InputParser";
import { leftPad } from "./Utils";
import Part from "./Part";
import { leftPad } from "./Utils";
export default class Day {
private part: String;
......@@ -14,11 +14,11 @@ export default class Day {
this.parser = parser;
}
getDay(): String {
public getDay(): String {
return this.day;
}
async getParts(): Promise<Array<Part>> {
public async getParts(): Promise<Part[]> {
if (this.part) {
return [
new Part(await this.getSolver(this.part), this.part),
......@@ -31,7 +31,7 @@ export default class Day {
}
}
async getInputs(): Promise<Array<InputFile>> {
public async getInputs(): Promise<InputFile[]> {
if (this.part) {
return [
await this.parser.parseFile(this.day, this.part),
......@@ -44,7 +44,7 @@ export default class Day {
}
}
async getSolver(part: String): Promise<{ default: Function}> {
public async getSolver(part: String): Promise<{ default: Function}> {
return await import(`./days/${this.day}/${part}`);
}
}
\ No newline at end of file
}
let enabled = false;
class Logger {
write(content: string): void {
if(enabled) {
public write(content: string): void {
if (enabled) {
process.stdout.write(content);
}
}
writeLine(content: string): void {
public writeLine(content: string): void {
if (enabled) {
this.write(`${content}\r\n`);
}
......@@ -20,4 +20,4 @@ export default instance;
export const enableLogger = () => {
enabled = true;
};
\ No newline at end of file
};
import InputFile from "./io/InputFile";
import { isArray, isFunction } from "util";
import InputFile from "./io/InputFile";
type Solver = { default: Function };
interface Solver { default: Function; }
export default class Part {
private solver: { default: Function };
......@@ -12,17 +12,17 @@ export default class Part {
this.number = number;
}
getNumber(): String {
public getNumber(): String {
return this.number;
}
run(input: InputFile): Array<any> {
let result = this.solver.default(input.getLines());
if(isArray(result)) {
public run(input: InputFile): any[] {
const result = this.solver.default(input.getLines());
if (isArray(result)) {
return result;
} else {
return [ result ];
}
}
}
\ No newline at end of file
}
......@@ -6,14 +6,14 @@ export const leftPad = (str: string, length: number, char: string) => {
return str;
};
export const equalArray = (a: Array<any>, b: Array<any>) => {
if (a === b) return true;
if (a == null || b == null) return false;
if (a.length !== b.length) return false;
export const equalArray = (a: any[], b: any[]) => {
if (a === b) { return true; }
if (a == null || b == null) { return false; }
if (a.length !== b.length) { return false; }
for(let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return false;
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) { return false; }
}
return true;
}
\ No newline at end of file
};
import { CommanderStatic } from 'commander';
import Client from '../Client';
import { leftPad } from '../Utils';
import * as fs from 'fs';
import { CommanderStatic } from "commander";
import * as fs from "fs";
import Client from "../Client";
import { leftPad } from "../Utils";
export default async (args: CommanderStatic) => {
const client = new Client(args.token);
const paddedDay = leftPad(args.args[0], 2, '0');
let template = fs.readFileSync('./src/days/template.ts', 'utf8');
const paddedDay = leftPad(args.args[0], 2, "0");
let template = fs.readFileSync("./src/days/template.ts", "utf8");
const input = await client.getInputForDay(Number(args.args[0]));
template = template.split('##DAY##').join(paddedDay);
template = template.split("##DAY##").join(paddedDay);
let exists = false;
try {
......@@ -24,8 +24,8 @@ export default async (args: CommanderStatic) => {
process.exit();
}
fs.writeFileSync(`./src/days/${paddedDay}/1.ts`, template.split('##PART##').join("1"));
fs.writeFileSync(`./src/days/${paddedDay}/2.ts`, template.split('##PART##').join("2"));
fs.writeFileSync(`./src/days/${paddedDay}/1.ts`, template.split("##PART##").join("1"));
fs.writeFileSync(`./src/days/${paddedDay}/2.ts`, template.split("##PART##").join("2"));
fs.writeFileSync(`./data/input/${paddedDay}-1.in`, input);
fs.writeFileSync(`./data/input/${paddedDay}-2.in`, input);
......
import SampleParser from '../io/SampleParser';
import InputParser from '../io/InputParser';
import InputFile from '../io/InputFile';
import SampleFile from '../io/SampleFile';
import { CommanderStatic } from 'commander';
import Day from '../Day';
import Part from '../Part';
import { equalArray } from '../Utils';
import { enableLogger } from '../Logger';
import { CommanderStatic } from "commander";
import Day from "../Day";
import InputFile from "../io/InputFile";
import InputParser from "../io/InputParser";
import SampleFile from "../io/SampleFile";
import SampleParser from "../io/SampleParser";
import { enableLogger } from "../Logger";
import Part from "../Part";
import { equalArray } from "../Utils";
export default async (args: CommanderStatic) => {
const parser: InputParser = args.sample ? new SampleParser() : new InputParser();
let parts: Array<Part> = [];
let inputs: Array<InputFile> = [];
const parts: Part[] = [];
const inputs: InputFile[] = [];
if(args.logging) {
if (args.logging) {
enableLogger();
}
......@@ -22,20 +22,20 @@ export default async (args: CommanderStatic) => {
inputs.push(... await day.getInputs());
parts.push(... await day.getParts());
for (let i = 0; i < parts.length; i++) {
const result = parts[i].run(inputs[i]);
if (args.sample) {
let expected = (<SampleFile>inputs[i]).getExpected();
const expected = (inputs[i] as SampleFile).getExpected();
if (equalArray(result, expected)) {
console.log(`Sample for Day ${day.getDay()} Part ${parts[i].getNumber()} passes: ${result} == ${expected}`);
} else {
console.error(`Sample for Day ${day.getDay()} Part ${parts[i].getNumber()} failes: ${result} != ${expected}`);
}
} else {
console.log(`${result.join('\n')}`);
console.log(`${result.join("\n")}`);
}
}
};
......@@ -2,17 +2,17 @@ import { Input } from "../../AoC";
export default (input: Input) => {
let frequenzy = 0;
let visitied = {};
const visitied = {};
while(true) {
while (true) {
for (let i = 0; i < input.length; i++) {
frequenzy += Number(input[i]);
if (visitied[frequenzy]) {
return frequenzy;
}
visitied[frequenzy] = true;
}
}
}
\ No newline at end of file
};
......@@ -18,28 +18,28 @@ export default (input: Input) => {
};
/**
*
*
* @param {String} line
* @returns {Boolean}
* @returns {Boolean}
*/
const containsTwos = (line) => {
return containsX(line, 2);
};
/**
*
*
* @param {String} line
* @returns {Boolean}
* @returns {Boolean}
*/
const containsThrees = (line) => {
return containsX(line, 3);
return containsX(line, 3);
};
const containsX = (line, count) => {
let chars = {};
const chars = {};
for(let i = 0; i < line.length; i++) {
let char = line.charAt(i);
for (let i = 0; i < line.length; i++) {
const char = line.charAt(i);
if (chars[char] === undefined) {
chars[char] = 1;
......@@ -48,11 +48,11 @@ const containsX = (line, count) => {
}
}
for (let c in chars) {
for (const c in chars) {
if (chars[c] === count) {
return true;
}
}
return false;
}
};
......@@ -2,12 +2,12 @@ import { Input } from "../../AoC";
export default (input: Input) => {
for (let a = 0; a < input.length; a++) {
for(let b = 0; b < input.length; b++) {
let diff = difference(input[a], input[b]);
for (let b = 0; b < input.length; b++) {
const diff = difference(input[a], input[b]);
if (diff.length === 1) {
let result = input[a].substr(0, diff[0]);
result += input[a].substr(diff[0]+1);
result += input[a].substr(diff[0] + 1);
return result;
}
}
......@@ -15,10 +15,10 @@ export default (input: Input) => {
};
/**
*
*
* @param {String} a
* @param {String} b
* @returns {Array<String>}
* @returns {Array<String>}
*/
const difference = (a, b) => {
const diff = [];
......@@ -28,6 +28,6 @@ const difference = (a, b) => {
diff.push(i);
}
}
return diff;
};
......@@ -5,15 +5,15 @@ const regex = /#(\d*)\s@\s(\d*),(\d*):\s(\d*)x(\d*)/;
export default (input: Input) => {
const map = [];
for(let i = 0; i < 1000; i++) {
for (let i = 0; i < 1000; i++) {
map[i] = [];
for(let j = 0; j < 1000; j++) {
for (let j = 0; j < 1000; j++) {
map[i][j] = 0;
}
}
for(let i = 0; i < input.length; i++) {
for (let i = 0; i < input.length; i++) {
const result = regex.exec(input[i]);
const x = Number(result[2]);
......@@ -26,9 +26,9 @@ export default (input: Input) => {
for (let yy = y; yy < y + height; yy++) {
map[xx][yy]++;
}
}
}
}
let counts = [].concat.apply([], map.filter(x => x !== undefined));
const counts = [].concat.apply([], map.filter((x) => x !== undefined));
return counts.filter((x) => x >= 2).length;
};
......@@ -8,17 +8,17 @@ export default (input: Input) => {
let claims = [];
for(let i = 0; i < 1000; i++) {
for (let i = 0; i < 1000; i++) {
map[i] = [];
claimMap[i] = [];
for(let j = 0; j < 1000; j++) {
for (let j = 0; j < 1000; j++) {
map[i][j] = 0;
claimMap[i][j] = null;
}
}
for(let i = 0; i < input.length; i++) {
for (let i = 0; i < input.length; i++) {
const result = regex.exec(input[i]);
const id = Number(result[1]);
......@@ -30,12 +30,12 @@ export default (input: Input) => {
const height = Number(result[5]);
let collission = false;
let toRemove = [];
const toRemove = [];
for (let xx = x; xx < x + width; xx++) {
for (let yy = y; yy < y + height; yy++) {
map[xx][yy]++;
if (map[xx][yy] > 1) {
collission = true;
toRemove.push(claimMap[xx][yy]);
......@@ -46,11 +46,11 @@ export default (input: Input) => {
}
if (collission) {
claims = claims.filter(x => !toRemove.includes(x));
claims = claims.filter((x) => !toRemove.includes(x));
} else {
claims.push(id);
}
}
return claims[0];
};
......@@ -11,11 +11,11 @@ const awake = /\[\d*-\d*-\d*\s\d\d:(\d\d)\]\swakes up/;
export default (input: Input) => {
input = input.sort((a, b) => {
let aa = date.exec(a);
let bb = date.exec(b);
const aa = date.exec(a);
const bb = date.exec(b);
let da = new Date(aa[1]);
let db = new Date(bb[1]);
const da = new Date(aa[1]);
const db = new Date(bb[1]);
return da.getTime() - db.getTime();
});
......@@ -59,7 +59,7 @@ export default (input: Input) => {
}
}
}
let gk = Object.keys(guards);
const gk = Object.keys(guards);
let highest = gk[0];
......@@ -73,8 +73,8 @@ export default (input: Input) => {
};
/**
*
* @param {Number[]} guard
*
* @param {Number[]} guard
*/
const getSum = (guard) => {
return guard.reduce((prev, val) => {
......@@ -83,7 +83,7 @@ const getSum = (guard) => {
};
const getMinute = (guard) => {
let minutes = Object.keys(guard);
const minutes = Object.keys(guard);
let highest = minutes[0];
......@@ -93,4 +93,4 @@ const getMinute = (guard) => {
}
}
return highest;
};
\ No newline at end of file
};
......@@ -8,11 +8,11 @@ const awake = /\[\d*-\d*-\d*\s\d\d:(\d\d)\]\swakes up/;
export default (input: Input) => {
input = input.sort((a, b) => {
let aa = date.exec(a);
let bb = date.exec(b);
const aa = date.exec(a);
const bb = date.exec(b);
let da = new Date(aa[1]);
let db = new Date(bb[1]);
const da = new Date(aa[1]);
const db = new Date(bb[1]);
return da.getTime() - db.getTime();
});
......@@ -56,7 +56,7 @@ export default (input: Input) => {
}
}
}
let gk = Object.keys(guards);
const gk = Object.keys(guards);
let highest = gk[0];
......@@ -70,11 +70,11 @@ export default (input: Input) => {
};
/**
*
* @param {Number[]} guard
*