From ae982483cbada4d7036e00f8f3eff194c0525fd4 Mon Sep 17 00:00:00 2001 From: Sergi Almacellas Abellana Date: Wed, 28 Nov 2018 17:38:57 +0100 Subject: [PATCH] Improve transform function docs and tests. Fixes #601 --- docs/docs.html | 2 +- tests/test-cases.js | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/docs/docs.html b/docs/docs.html index bd842f1..1da2126 100644 --- a/docs/docs.html +++ b/docs/docs.html @@ -545,7 +545,7 @@ var csv = Papa.unparse({ transform - A function to apply on each value. The function receives the value as its first argument and the column number as its second argument. The return value of the function will replace the value it received. The transform function is applied before dynamicTyping. + A function to apply on each value. The function receives the value as its first argument and the column number or header name when enabled as its second argument. The return value of the function will replace the value it received. The transform function is applied before dynamicTyping. diff --git a/tests/test-cases.js b/tests/test-cases.js index 7e4986c..69b9b25 100644 --- a/tests/test-cases.js +++ b/tests/test-cases.js @@ -913,6 +913,39 @@ var PARSE_TESTS = [ errors: [] } }, + { + description: "Custom transform accepts column number also", + input: 'A,B,C\r\nd,e,f', + config: { + transform: function(value, column) { + if (column % 2) { + value = value.toLowerCase(); + } + return value; + } + }, + expected: { + data: [["A","b","C"], ["d","e","f"]], + errors: [] + } + }, + { + description: "Custom transform accepts header name when using header", + input: 'A,B,C\r\nd,e,f', + config: { + header: true, + transform: function(value, name) { + if (name === 'B') { + value = value.toUpperCase(); + } + return value; + } + }, + expected: { + data: [{'A': "d", 'B': "E", 'C': "f"}], + errors: [] + } + }, { description: "Dynamic typing converts ISO date strings to Dates", input: 'ISO date,long date\r\n2018-05-04T21:08:03.269Z,Fri May 04 2018 14:08:03 GMT-0700 (PDT)\r\n2018-05-08T15:20:22.642Z,Tue May 08 2018 08:20:22 GMT-0700 (PDT)',