-
Notifications
You must be signed in to change notification settings - Fork 0
/
csv.ts
55 lines (48 loc) · 1.32 KB
/
csv.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
import {parse, stringify} from "../../deps.pure_ext.ts";
import {primitiveParseX} from "../pure/primitive.ts";
/**
* Convert from object array to CSV string.
* @see https://deno.land/std/csv
* @example
* ```ts
* const csv = csvEncode([{
* aaa: 123,
* bbb: true
* }]);
* ```
*/
export function csvEncode<T extends Record<keyof T, string | number | boolean>>(data:T[], bom?:boolean):string{
return stringify(data, {
bom: bom,
columns: Object.keys(data[0])
}).replace(/\r/g, "").trim();
}
/**
* Convert from CSV string to object array.
* If parsing failed of cell value use default (`def`) value.
* Convert to same type as default value.
* @see https://deno.land/std/csv
* @example
* ```ts
* const list = csvDecode("aaa,bbb\n123,true", {
* aaa: 0,
* bbb: false
* });
* ```
*/
export function csvDecode<T extends Record<keyof T, string | number | boolean>>(data:string, def:T):T[]{
const csv = parse(data, {
skipFirstRow: true,
trimLeadingSpace: true
});
const records:T[] = [];
for(const element of csv){
const props:Partial<T> = {};
type K = keyof T;
for(const [k, v] of Object.entries(element)){
props[<K>k] = <T[K]>primitiveParseX(v, def[<K>k]);
}
records.push(structuredClone(<T>props));
}
return records;
}