(csv, options, reviver = v => v)
| 23 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 24 | */ |
| 25 | export function parse (csv, options, reviver = v => v) { |
| 26 | const ctx = Object.create(null); |
| 27 | ctx.options = options || {}; |
| 28 | ctx.reviver = reviver; |
| 29 | ctx.value = ''; |
| 30 | ctx.entry = []; |
| 31 | ctx.output = []; |
| 32 | ctx.col = 1; |
| 33 | ctx.row = 1; |
| 34 | |
| 35 | ctx.options.delimiter = ctx.options.delimiter === undefined ? '"' : options.delimiter; |
| 36 | if(ctx.options.delimiter.length > 1 || ctx.options.delimiter.length === 0) |
| 37 | throw Error(`CSVError: delimiter must be one character [${ctx.options.separator}]`); |
| 38 | |
| 39 | ctx.options.separator = ctx.options.separator === undefined ? ',' : options.separator; |
| 40 | if(ctx.options.separator.length > 1 || ctx.options.separator.length === 0) |
| 41 | throw Error(`CSVError: separator must be one character [${ctx.options.separator}]`); |
| 42 | |
| 43 | const lexer = new RegExp(`${escapeRegExp(ctx.options.delimiter)}|${escapeRegExp(ctx.options.separator)}|\r\n|\n|\r|[^${escapeRegExp(ctx.options.delimiter)}${escapeRegExp(ctx.options.separator)}\r\n]+`, 'y'); |
| 44 | const isNewline = /^(\r\n|\n|\r)$/; |
| 45 | |
| 46 | let matches = []; |
| 47 | let match = ''; |
| 48 | let state = 0; |
| 49 | |
| 50 | while ((matches = lexer.exec(csv)) !== null) { |
| 51 | match = matches[0]; |
| 52 | |
| 53 | switch (state) { |
| 54 | case 0: // start of entry |
| 55 | switch (true) { |
| 56 | case match === ctx.options.delimiter: |
| 57 | state = 3; |
| 58 | break; |
| 59 | case match === ctx.options.separator: |
| 60 | state = 0; |
| 61 | valueEnd(ctx); |
| 62 | break; |
| 63 | case isNewline.test(match): |
| 64 | state = 0; |
| 65 | valueEnd(ctx); |
| 66 | entryEnd(ctx); |
| 67 | break; |
| 68 | default: |
| 69 | ctx.value += match; |
| 70 | state = 2; |
| 71 | break; |
| 72 | } |
| 73 | break; |
| 74 | case 2: // un-delimited input |
| 75 | switch (true) { |
| 76 | case match === ctx.options.separator: |
| 77 | state = 0; |
| 78 | valueEnd(ctx); |
| 79 | break; |
| 80 | case isNewline.test(match): |
| 81 | state = 0; |
| 82 | valueEnd(ctx); |
no test coverage detected