Browse Source

add ability to configure which columns are dynamically typed

pull/288/merge
vyrak bunleang 8 years ago committed by Sergi Almacellas Abellana
parent
commit
f8255fdf51
  1. 22
      papaparse.js
  2. 18
      tests/test-cases.js

22
papaparse.js

@ -193,7 +193,7 @@
function CsvToJson(_input, _config) function CsvToJson(_input, _config)
{ {
_config = _config || {}; _config = _config || {};
_config.dynamicTyping = _config.dynamicTyping || false; _config.dynamicTyping = new DynamicTypingConfig(_config.dynamicTyping);
if (_config.worker && Papa.WORKERS_SUPPORTED) if (_config.worker && Papa.WORKERS_SUPPORTED)
{ {
@ -415,6 +415,24 @@
} }
} }
function DynamicTypingConfig(config)
{
this._config = config;
}
DynamicTypingConfig.prototype.constructor = DynamicTypingConfig;
DynamicTypingConfig.prototype.isIncluded = function(field)
{
if (typeof this._config === 'function')
{
return this._config(field) === true;
}
if (typeof this._config === 'object')
{
return this._config[field] === true;
}
return !!this._config;
};
/** ChunkStreamer is the base prototype for various streamer implementations. */ /** ChunkStreamer is the base prototype for various streamer implementations. */
function ChunkStreamer(config) function ChunkStreamer(config)
{ {
@ -969,7 +987,7 @@
function parseDynamic(field, value) function parseDynamic(field, value)
{ {
if ((_config.dynamicTyping[field] || _config.dynamicTyping) === true) if (_config.dynamicTyping.isIncluded(field))
{ {
if (value === 'true' || value === 'TRUE') if (value === 'true' || value === 'TRUE')
return true; return true;

18
tests/test-cases.js

@ -693,6 +693,24 @@ var PARSE_TESTS = [
}] }]
} }
}, },
{
description: "Dynamic typing by indices can be determined by function",
input: '001,002,003',
config: { dynamicTyping: function(field) { return (field % 2) === 0; } },
expected: {
data: [[1, "002", 3]],
errors: []
}
},
{
description: "Dynamic typing by headers can be determined by function",
input: 'A_as_int,B,C_as_int\r\n001,002,003',
config: { header: true, dynamicTyping: function(field) { return /_as_int$/.test(field); } },
expected: {
data: [{"A_as_int": 1, "B": "002", "C_as_int": 3}],
errors: []
}
},
{ {
description: "Blank line at beginning", description: "Blank line at beginning",
input: '\r\na,b,c\r\nd,e,f', input: '\r\na,b,c\r\nd,e,f',

Loading…
Cancel
Save