-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
72 lines (66 loc) · 1.7 KB
/
Copy pathindex.js
File metadata and controls
72 lines (66 loc) · 1.7 KB
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
// @ts-check
/** download txt file
* @param {Blob} content - content of the file
* @param {string} filename - name of the file
*/
function save(content, filename) {
const anchor = document.createElement('a')
anchor.href = URL.createObjectURL(content)
anchor.download = filename
anchor.click()
}
/** download txt file
* @param {string} content - content of the file
* @param {string} filename - name of the file
*/
export
function export_txt (content, filename) {
save(new Blob([content]), filename)
}
class Error_csv extends Error {
constructor() {
super('invalid records or columns')
}
}
/** download csv file
* @param {{
* columns?: string[],
* records: any[][],
* filename: string,
* skip_validate?: boolean,
* }} options
*/
export
function export_csv({
columns,
records,
filename,
skip_validate = false,
}) {
if (!skip_validate) { // if: 不跳过校验
const length = columns?.length ?? records[0]?.length
if (length !== undefined) // if: 有数据
for (const r of records)
if (r.length !== length)
throw new Error_csv()
}
/** Item
* + CSV 中的字段们之间用逗号隔开
* + 字段里如果有逗号,则须用双引号包起字段
* + 如果字段内部有双引号(与“包起字段的双引号”冲突),须用在“出现在字段中的双引号”前,加一个双引号
*/
const Item = raw => {
if (typeof raw !== 'string')
raw = String(raw)
return '"' + raw.replaceAll('"', '""') + '"'
}
const list = []
if (columns)
list.push(columns.map(Item).join(','))
list.push(...
records.map(
record => record.map(Item).join(',')
)
)
export_txt(list.join('\n'), filename)
}