This repository has been archived by the owner on May 30, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.ts
81 lines (77 loc) · 1.97 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
import { readAll } from "https://deno.land/std/encoding/csv.ts";
import { readFileStr } from "https://deno.land/std/fs/read_file_str.ts";
import { StringReader } from "https://deno.land/std/io/readers.ts";
import { BufReader } from "https://deno.land/std/io/bufio.ts";
export interface HeaderOption {
name: string;
parse?: (input: string) => unknown;
}
export interface ParseOption {
header: boolean | string[] | HeaderOption[];
parse?: (input: unknown) => unknown;
}
export async function parse(
input: string,
opt: ParseOption = { header: false }
): Promise<unknown[]> {
const [r, err] = await readAll(new BufReader(new StringReader(input)));
if (err) throw err;
if (opt.header) {
let headers: HeaderOption[] = [];
let i = 0;
if (Array.isArray(opt.header)) {
if (typeof opt.header[0] !== "string") {
headers = opt.header as HeaderOption[];
} else {
const h = opt.header as string[];
headers = h.map(
(e): HeaderOption => {
return {
name: e
};
}
);
}
} else {
headers = r.shift().map(
(e): HeaderOption => {
return {
name: e
};
}
);
i++;
}
return r.map(
(e): unknown => {
if (e.length !== headers.length) {
throw `Error number of fields line:${i}`;
}
i++;
let out = {};
for (let j = 0; j < e.length; j++) {
const h = headers[j];
if (h.parse) {
out[h.name] = h.parse(e[j]);
} else {
out[h.name] = e[j];
}
}
if (opt.parse) {
return opt.parse(out);
}
return out;
}
);
}
if (opt.parse) {
return r.map((e: string[]): unknown => opt.parse(e));
}
return r;
}
export async function parseFile(
file: string,
opt: ParseOption = { header: false }
): Promise<unknown[]> {
return parse(await readFileStr(file), opt);
}