Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nafeu/371d1da439cfe579555acffeeddbc3f4 to your computer and use it in GitHub Desktop.
Save nafeu/371d1da439cfe579555acffeeddbc3f4 to your computer and use it in GitHub Desktop.
const recursivelyUpdateTable = ({ tableData, childData, id }) => {
return insertIntoTable({
existingRows: tableData,
subRowsToInsert: childData,
path: id.split('.')
});
}
const insertIntoTable = ({ existingRows, subRowsToInsert, path }) => {
const id = path[0];
let updatedRows;
const isBaseCase = path.length === 1;
if (isBaseCase) {
return existingRows.map((row, index) => {
const isMatchedRowWithoutSubRows = index === Number(id) && !row.subRows;
if (isMatchedRowWithoutSubRows) {
return {
...row,
subRows: subRowsToInsert
}
}
return row;
});
}
return existingRows.map((row, index) => {
const isMatchedRowWithSubRows = index === Number(id) && row.subRows;
if (isMatchedRowWithSubRows) {
const [, ...updatedPath] = path;
return {
...row,
subRows: insertIntoTable({
existingRows: row.subRows,
subRowsToInsert,
path: updatedPath
})
}
}
return row;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment