blob: a89434b2c9e2c835328c059d1f59755659c5833d (
plain)
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
|
import { Frame } from '../index';
import { isValidJSONObject } from '../helpers/arrayFunctions';
import { readFileSync } from 'fs';
/**
* flattenArray - flattens a 2D into a single array
* @param array: the array to be flattened
* @returns the flattened array
*/
export function flatten(array: any[][]): any[] {
let flattenedArray: any[] = [];
for (let i = 0; i < array.length; i++) {
if (Array.isArray(array[i])) {
flattenedArray = flattenedArray.concat(flatten(array[i]));
} else {
flattenedArray.push(array[i]);
}
}
return flattenedArray;
}
/**
* fromJSON - converts a JSON string into a rowdata - framedata is a 2D array
* @param json: the JSON string to be converted
* @returns the rowdata
*/
export function fromJSON(this: Frame, json: any): Frame {
if (isValidJSONObject(json)) {
const header: string[] = [];
const rowdata: any[][] = [];
// loop through each row
for (let i = 0; i < json.length; i++) {
// get all the keys and store them in the header
for (const key in json[i]) {
if (!header.includes(key)) {
header.push(key);
}
}
}
// loop through each row
for (let i = 0; i < json.length; i++) {
// get the values of the keys present in the header, if the values are not present in the row, add null
const row: any[] = [];
for (let j = 0; j < header.length; j++) {
if (json[i][header[j]] !== undefined) {
row.push(json[i][header[j]]);
} else {
row.push(null);
}
}
rowdata.push(row);
}
this.rowdata = rowdata;
this.columns = header;
return this;
} else {
throw new Error('Invalid JSON');
}
}
/**
* fromCSV - converts a CSV string into a rowdata - framedata is a 2D array
* @param csv: the CSV string to be converted
* @returns the rowdata
*/
export function fromCSV(this: Frame, csvpath: string): Frame {
// read the csv file
const csv = readFileSync(csvpath, 'utf8');
const rowdata: any[][] = [];
const rows: string[] = csv.split('\n');
for (let i = 0; i < rows.length; i++) {
const row: string[] = rows[i].split(',');
rowdata.push(row);
}
this.rowdata = rowdata;
if (this.columns.length === 0) {
this.columns = rowdata[0];
}
// remove the first row
this.rowdata.shift();
// if last row contains only empty values, remove it
if (this.rowdata[this.rowdata.length - 1].every((item) => item === '')) {
this.rowdata.pop();
}
return this;
}
|