import type Transform from './Transform.js'; import { getProp, setProp, unsetProp } from './utils.js'; function getUnwindablePaths( obj: T, currentPath?: string, unwindablePaths = new Set(), ): Set { return Object.keys(obj).reduce( (unwindablePaths: Set, key: string) => { const newPath = currentPath ? `${currentPath}.${key}` : key; const value = obj[key as keyof T]; if ( typeof value === 'object' && value !== null && !Array.isArray(value) && Object.prototype.toString.call((value as any).toJSON) !== '[object Function]' && Object.keys(value).length ) { getUnwindablePaths(value, newPath, unwindablePaths); } else if (Array.isArray(value)) { unwindablePaths.add(newPath); for (const arrObj of value) { if (typeof arrObj === 'object' && arrObj !== null) { getUnwindablePaths(arrObj, newPath, unwindablePaths); } } } return unwindablePaths; }, unwindablePaths, ); } export interface UnwindOptions { paths?: ReadonlyArray; blankOut?: boolean; } /** * Performs the unwind recursively in specified sequence * * @param {String[]} unwindPaths The paths as strings to be used to deconstruct the array * @returns {Object => Array} Array of objects containing all rows after unwind of chosen paths */ export default function unwind< I extends object = object, O extends object = object, >(opts: UnwindOptions = {}): Transform { function unwindReducer( rows: Array, unwindPath: string, ): Array { return rows.flatMap((row) => { const unwindArray = getProp(row, unwindPath); if (!Array.isArray(unwindArray)) { return row; } if (!unwindArray.length) { return unsetProp(row, unwindPath); } const baseNewRow = opts.blankOut ? {} : row; const [firstRow, ...restRows] = unwindArray; return [ setProp(row, unwindPath, firstRow), ...restRows.map((unwindRow) => setProp(baseNewRow, unwindPath, unwindRow), ), ]; }); } const paths = Array.isArray(opts.paths) ? opts.paths : opts.paths ? [opts.paths] : undefined; return (dataRow: I) => (paths || Array.from(getUnwindablePaths(dataRow))).reduce(unwindReducer, [ dataRow, ]) as unknown as Array; }