-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.ts
95 lines (83 loc) · 2.42 KB
/
mod.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
89
90
91
92
93
94
95
import { parseArgs } from "@std/cli/parse-args";
import memoize from "@korkje/memz";
import { Aocd } from "./Aocd.ts";
import { DefaultAocdSource } from "./DefaultAocdSource.ts";
import type {
AocdSource,
Config,
Options,
PartResult,
Solver,
} from "./_common.ts";
export type * from "./_common.ts";
export { version } from "./version.ts";
export { Aocd };
let globalConfig: Partial<Config> | undefined;
/**
* Use this if you want to manually configure Aocd options programmatically or
* if you want to configure where Aocd gets its data from. Throws an error if
* the Aocd singleton has already been configured or instantiated.
*/
export function configureAocd(config: Partial<Config>) {
if (globalConfig) {
throw new Error(
"configureAocd() may not be called when Aocd is already configured",
);
}
globalConfig = config;
}
let singleton: Aocd | undefined;
const parsedArgs = memoize(() =>
parseArgs(Deno.args, {
boolean: ["s", "submit", "t", "time"],
string: ["input"],
})
);
/**
* Main entrypoint into this library. Returns an automatically configured
* Aocd singleton instance.
*
* The configuration is based on values previously passed to
* {@link configureAocd} or CLI parameters inside `Deno.args`.
*/
export function getAocd(): Aocd {
if (singleton) {
return singleton;
}
singleton = new Aocd(constructConfig());
return singleton;
}
function constructConfig(): Config {
// If globalConfig wasn't already set, set it to signal to future calls of
// `configureAocd()` that it's too late to configure Aocd.
const explicitlySetConfig: Partial<Config> = globalConfig ??= {};
return {
options: explicitlySetConfig.options ?? optionsFromCLI(),
source: explicitlySetConfig.source ?? sourceFromCLI(),
};
}
function optionsFromCLI(): Partial<Options> {
const p = parsedArgs();
const submit = Boolean(p.s || p.submit);
const time = Boolean(p.t || p.time);
return { submit, time };
}
function sourceFromCLI(): AocdSource {
const p = parsedArgs();
const inputFile: string | undefined = p.input;
return new DefaultAocdSource({ inputFile });
}
/**
* Run a solver with a given day's input.
*
* This method is a shortcut for calling the {@link Aocd.runPart} method of
* the {@link getAocd} return value.
*/
export function runPart(
year: number,
day: number,
part: number,
solver: Solver,
): Promise<PartResult> {
return getAocd().runPart(year, day, part, solver);
}