Skip to content
Permalink
Browse files

Feat/onPreParse (#130)

* Fix implementation - If defined, onPreParse should mutate the raw csv string.
* Add tests
* Update documentation
  • Loading branch information...
evanplaice committed May 2, 2019
1 parent 368d1b4 commit ad9f49b66649f64e98284cec28eaae16023c633d
Showing with 48 additions and 3 deletions.
  1. +1 −1 docs/hooks-callbacks.md
  2. +2 −2 src/jquery.csv.js
  3. +45 −0 test/csv.on_pre_parse_hook.js
@@ -23,7 +23,7 @@ This hook is called before the parser starts processing the dataset. Useful if y

```javascript
// strips empty (illegal) lines from the data before parsing
var removeEmptyLines = function(csv) {
var removeEmptyLines = function(csv, state) {
var lines = $.csv.splitLines(csv);
var output = [];
for(var i=0, len=lines.length; i<len; i++) {
@@ -714,7 +714,7 @@ RegExp.escape = function (s) {

// onPreParse hook
if (options.onPreParse !== undefined) {
options.onPreParse(csv, options.state);
csv = options.onPreParse(csv, options.state);
}

// parse the data
@@ -806,7 +806,7 @@ RegExp.escape = function (s) {

// onPreParse hook
if (options.onPreParse !== undefined) {
options.onPreParse(csv, options.state);
csv = options.onPreParse(csv, options.state);
}

// parse the csv
@@ -0,0 +1,45 @@
const test = require('tape');
const csv = require('../src/jquery.csv.js');
const fixtures = require('./fixtures/fixtures.js');

test('$.csv.toObjects onPreParse hook callback - should be passed the raw csv and state', (t) => {
let passedCSV, passedState;

csv.toObjects(fixtures.objects_csv, { onPreParse: (csv, state) => {
passedCSV = csv;
passedState = state;
return csv;
} });

t.isNot(passedCSV, null, 'data argument should not be null');
t.isNot(passedState, null, 'state argument should not be null');
t.end();
});

test('$.csv.toArrays onPreParse hook callback - should be passed the raw csv and state', (t) => {
let passedCSV, passedState;

csv.toArrays(fixtures.arrays1_csv, { onPreParse: (csv, state) => {
passedCSV = csv;
passedState = state;
return csv;
} });

t.isNot(passedCSV, null, 'data argument should not be null');
t.isNot(passedState, null, 'state argument should not be null');
t.end();
});

test('$.csv.toObjects onPreParse hook callback - should affect return value', (t) => {
const returnEmptyCSV = () => 'header\n""';
const result = csv.toObjects(fixtures.objects_csv,{ onPreParse: returnEmptyCSV });
t.deepEqual(result, [{ header: '' }], 'return value should reflect what was returned from callback');
t.end();
});

test('$.csv.toArrays onPreParse hook callback - should affect return value', (t) => {
const returnEmptyCSV = () => '';
const result = csv.toArrays(fixtures.arrays1_csv, { onPreParse: returnEmptyCSV });
t.deepEqual(result, [], 'return value should reflect what was returned from callback');
t.end();
});

0 comments on commit ad9f49b

Please sign in to comment.
You can’t perform that action at this time.