commit 0a007862e7f91606c4a7a364a898665c280dcc13 Author: Dominic Masters Date: Wed Dec 23 22:43:44 2020 +1100 Added micro parser diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..d648349 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2020 Dominic Masters. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..2b3ab21 --- /dev/null +++ b/README.md @@ -0,0 +1,13 @@ +# Micro CSV +Micro CSV Parser for JavaScript and Google Script. Designed to be small, +efficient and no dependencies. + +## Usage +Only one method is provided; +```js +const csv = 'Name,Age,Location\nDom,26,Sydney\nSteve,30,New York'; +parseCSV(csv, function(line) { + console.log(line.name);//Dom then Steve +}) +``` +To stay efficient we ask for a callback that is fired for every line parsed. \ No newline at end of file diff --git a/src/index.js b/src/index.js new file mode 100644 index 0000000..6460a4c --- /dev/null +++ b/src/index.js @@ -0,0 +1,43 @@ +function parseCSV(csv, onLine) { + const lines = csv.split(/\r?\n/); + let headers = null; + + for(let i = 0; i < lines.length; i++) { + let line = lines[i].trim(); + if(!line.length) continue; + + let lineArray = []; + let currentValue = ''; + let encapsulated = false; + + for(let j = 0; j < line.length; j++) { + let c = line[j]; + + if(!encapsulated && c == ',') { + //Comma, make new cell + lineArray.push(currentValue); + currentValue = ''; + continue; + } else if(c == '"') { + //Quote, begin string encapsulation + encapsulated = !encapsulated; + continue; + } + currentValue += `${c}`; + } + lineArray.push(currentValue); + + //Is this the headers? + if(!headers) { + headers = lineArray; + continue; + } + + //This is a line + let x = {}; + for(let j = 0; j < headers.length; j++) { + x[headers[j]] = lineArray[j] || ''; + } + onLine(x); + } +} \ No newline at end of file