Created
May 11, 2021 17:11
-
-
Save umcconnell/f349002ce9d29c59dbb1986a20b990a6 to your computer and use it in GitHub Desktop.
CSV Parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let csv = ` | |
year,amount,n | |
2016,123,1 | |
2017,124,2 | |
2018,125,3 | |
2019,126,4 | |
2020,127,5 | |
2021,128,6 | |
`; | |
let is_empty = x => !x; | |
function parse_csv(csv, { newline = "\n", seperator = ",", ignore_missing = true, header = undefined } = {}) { | |
let lines = csv.split(newline).filter(l => !is_empty(l)).map(l => l.split(seperator)); | |
header = header || lines.shift(); | |
return lines.map((line, i) => Object.fromEntries( | |
header.map((key, j) => { | |
if (j > (line.length - 1) && !ignore_missing) throw new Error(`Missing element in data row ${i+1}, col ${j+1}`); | |
return [key, line[j]]; | |
}) | |
)) | |
} | |
console.log(parse_csv(csv)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment