aboutsummaryrefslogtreecommitdiff
path: root/src/lib
diff options
context:
space:
mode:
authorPriyansh <[email protected]>2022-01-22 21:57:21 -0500
committerPriyansh <[email protected]>2022-01-22 21:57:21 -0500
commit4700bb0fafd7c7b208168dda7425193bfe1eb4db (patch)
treedcf053a8ba156f24ee2ea4e121f3d77be2c7294f /src/lib
parent5dfd3ad1f2fb4bbc0bf7b92ac93f59ccd78a7fc4 (diff)
downloadizuku.js-4700bb0fafd7c7b208168dda7425193bfe1eb4db.tar.xz
izuku.js-4700bb0fafd7c7b208168dda7425193bfe1eb4db.zip
feat: function to readCSV
Diffstat (limited to 'src/lib')
-rw-r--r--src/lib/data.ts29
1 files changed, 29 insertions, 0 deletions
diff --git a/src/lib/data.ts b/src/lib/data.ts
index 9649d6d..a89434b 100644
--- a/src/lib/data.ts
+++ b/src/lib/data.ts
@@ -1,5 +1,6 @@
import { Frame } from '../index';
import { isValidJSONObject } from '../helpers/arrayFunctions';
+import { readFileSync } from 'fs';
/**
* flattenArray - flattens a 2D into a single array
@@ -56,3 +57,31 @@ export function fromJSON(this: Frame, json: any): Frame {
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;
+}