-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathio.ts
38 lines (30 loc) · 897 Bytes
/
io.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
import {createReadStream } from 'fs'
import { createInterface } from 'readline'
import { operations, Instruction, Operation } from './util';
export const readlines = async (file: string): Promise<string[]> => {
const fileStream = createReadStream(file);
const rl = createInterface({
input: fileStream,
crlfDelay: Infinity
});
let result = []
for await (const line of rl) {
result.push(line)
}
return result
}
export const parseProgram = (lines: string[]): Instruction[] => {
const validOps = operations.join('|')
// You could do this in one regex across the entire file
const re = new RegExp(`^(?<op>(${validOps})) (?<arg>[-+]\\d+)$`)
return lines.map(line => {
const match = re.exec(line)
const op = match.groups.op
const arg = match.groups.arg
// TODO: assert
return {
op: op as Operation,
arg: parseInt(arg)
}
})
}