From 341ef37205b6269ded628b458f85607eba8f0b4c Mon Sep 17 00:00:00 2001 From: ztimson Date: Sat, 9 Nov 2024 16:30:05 -0500 Subject: [PATCH] Added fromCsv --- index.html | 9 +++++++-- package.json | 2 +- src/csv.ts | 19 ++++++++++++++++++- src/string.ts | 8 ++++---- 4 files changed, 30 insertions(+), 8 deletions(-) diff --git a/index.html b/index.html index fbee56e..d13bcd3 100644 --- a/index.html +++ b/index.html @@ -6,9 +6,14 @@ diff --git a/package.json b/package.json index 5d85bfa..90a7c45 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@ztimson/utils", - "version": "0.22.4", + "version": "0.22.5", "description": "Utility library", "author": "Zak Timson", "license": "MIT", diff --git a/src/csv.ts b/src/csv.ts index 87736db..8395498 100644 --- a/src/csv.ts +++ b/src/csv.ts @@ -1,5 +1,22 @@ import {ASet} from './aset.ts'; -import {dotNotation, flattenObj, JSONAttemptParse, JSONSanitize} from './objects.ts'; +import {dotNotation, flattenObj, JSONSanitize} from './objects.ts'; + +export function fromCsv(csv: string, hasHeaders=true): T[] { + const row = csv.split('\n'); + let headers: any = hasHeaders ? row.splice(0, 1)[0] : null; + if(headers) headers = headers.match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g); + return row.map(r => { + const props: string[] = r.match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g); + const h = headers || (Array(props.length).fill(null).map((r, i) => { + let letter = ''; + const first = i / 26; + if(first > 1) letter += + i % 26 + i + })); + return h.reduce((acc: any, h: any, i: number) => ({...acc, [h]: props[i]}), {}) + }) +} /** * Convert an object to a CSV string diff --git a/src/string.ts b/src/string.ts index e8e5392..fd0033e 100644 --- a/src/string.ts +++ b/src/string.ts @@ -1,22 +1,22 @@ /** * String of all letters */ -const LETTER_LIST = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; +export const LETTER_LIST = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; /** * String of all numbers */ -const NUMBER_LIST = '0123456789'; +export const NUMBER_LIST = '0123456789'; /** * String of all symbols */ -const SYMBOL_LIST = '~`!@#$%^&*()_-+={[}]|\\:;"\'<,>.?/'; +export const SYMBOL_LIST = '~`!@#$%^&*()_-+={[}]|\\:;"\'<,>.?/'; /** * String of all letters, numbers & symbols */ -const CHAR_LIST = LETTER_LIST + NUMBER_LIST + SYMBOL_LIST; +export const CHAR_LIST = LETTER_LIST + LETTER_LIST.toLowerCase() + NUMBER_LIST + SYMBOL_LIST; /** * Convert number of bytes into a human-readable size