Skip to content

Commit

Permalink
fix: Avoid redundant deep cloning when unwinding. (#286)
Browse files Browse the repository at this point in the history
* Avoid redundant deep cloning when unwinding.

* Attempt to improve readability of unwindData(...)

* Improve formatting.
  • Loading branch information
jarib authored and knownasilya committed Apr 16, 2018
1 parent 61d9808 commit 95a6ca9
Showing 1 changed file with 32 additions and 29 deletions.
61 changes: 32 additions & 29 deletions lib/JSON2CSVBase.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ class JSON2CSVBase {
*/
processRow(row) {
if (!row
|| (Object.getOwnPropertyNames(row).length === 0
|| (Object.getOwnPropertyNames(row).length === 0
&& !this.opts.includeEmptyRows)) {
return undefined;
}
Expand Down Expand Up @@ -114,7 +114,7 @@ class JSON2CSVBase {
const defaultValue = typeof fieldInfo === 'object' && 'default' in fieldInfo
? fieldInfo.default
: this.opts.defaultValue;

let value;
if (fieldInfo) {
if (typeof fieldInfo === 'string') {
Expand Down Expand Up @@ -231,42 +231,45 @@ class JSON2CSVBase {
* @param {Object} dataRow Original JSON object
* @param {String[]} unwindPaths The paths as strings to be used to deconstruct the array
* @returns {Array} Array of objects containing all rows after unwind of chosen paths
*/
*/
unwindData(dataRow, unwindPaths) {
return unwindPaths
.reduce((data, unwindPath) =>
data.map((dataEl) => {
const unwindArray = lodashGet(dataEl, unwindPath);
const unwind = (rows, unwindPath) => {
function clone(o) {
return unwindPath.indexOf('.') !== -1
? lodashCloneDeep(o)
: Object.assign({}, o);
}

return rows
.map(row => {
const unwindArray = lodashGet(row, unwindPath);

if (!Array.isArray(unwindArray)) {
return dataEl;
return row;
}

if (unwindArray.length) {
return unwindArray.map((unwindEl, index) => {
const dataCopy = lodashCloneDeep(dataEl);
if (!unwindArray.length) {
return lodashSet(clone(row), unwindPath, undefined);
}

if (this.opts.unwindBlank && index > 0) {
Object.keys(dataCopy).forEach(key => {
if (!unwindEl[key]) {
dataCopy[key] = null;
}
})
}
return unwindArray.map((unwindRow, index) => {
const clonedRow = clone(row);
const shouldBlank = this.opts.unwindBlank && index > 0;

if (shouldBlank) {
const parentKeys = Object.keys(clonedRow).filter(
key => !unwindRow[key]
);
parentKeys.forEach(key => (clonedRow[key] = null));
}

lodashSet(dataCopy, unwindPath, unwindEl);
return dataCopy;
});
}
return lodashSet(clonedRow, unwindPath, unwindRow);
});
})
.reduce((a, e) => a.concat(e), []);
};

const dataCopy = lodashCloneDeep(dataEl);
lodashSet(dataCopy, unwindPath, undefined);
return dataCopy;
}).reduce((tempData, rows) => tempData.concat(rows), []),
[dataRow]
)
.reduce((tempData, rows) => tempData.concat(rows), []);
return unwindPaths.reduce(unwind, [dataRow]);
}
}

Expand Down

0 comments on commit 95a6ca9

Please sign in to comment.