From f8255fdf516f6d93a5e61019452985be1b24a993 Mon Sep 17 00:00:00 2001 From: vyrak bunleang Date: Tue, 4 Apr 2017 12:12:22 -0600 Subject: [PATCH] add ability to configure which columns are dynamically typed --- papaparse.js | 22 ++++++++++++++++++++-- tests/test-cases.js | 18 ++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/papaparse.js b/papaparse.js index 255d2ea..c3e3e56 100644 --- a/papaparse.js +++ b/papaparse.js @@ -193,7 +193,7 @@ function CsvToJson(_input, _config) { _config = _config || {}; - _config.dynamicTyping = _config.dynamicTyping || false; + _config.dynamicTyping = new DynamicTypingConfig(_config.dynamicTyping); 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. */ function ChunkStreamer(config) { @@ -969,7 +987,7 @@ function parseDynamic(field, value) { - if ((_config.dynamicTyping[field] || _config.dynamicTyping) === true) + if (_config.dynamicTyping.isIncluded(field)) { if (value === 'true' || value === 'TRUE') return true; diff --git a/tests/test-cases.js b/tests/test-cases.js index 81f3d53..f9e93ea 100644 --- a/tests/test-cases.js +++ b/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", input: '\r\na,b,c\r\nd,e,f',