( oldData: unknown, deletePath: Array<string>, )
| 321 | * @returns newData without the deleted items by path |
| 322 | */ |
| 323 | export const deleteNestedDataByPath = ( |
| 324 | oldData: unknown, |
| 325 | deletePath: Array<string>, |
| 326 | ): any => { |
| 327 | const type = getNativeObjectType(oldData) |
| 328 | if (type === 'Map') { |
| 329 | const newData = new Map<unknown, unknown>( |
| 330 | Map.prototype.entries.call(oldData), |
| 331 | ) |
| 332 | |
| 333 | if (deletePath.length === 1) { |
| 334 | newData.delete(deletePath[0]) |
| 335 | return newData |
| 336 | } |
| 337 | |
| 338 | const [head, ...tail] = deletePath |
| 339 | newData.set(head, deleteNestedDataByPath(newData.get(head), tail)) |
| 340 | return newData |
| 341 | } |
| 342 | |
| 343 | if (type === 'Set') { |
| 344 | const setAsArray = deleteNestedDataByPath( |
| 345 | Array.from(Set.prototype.values.call(oldData)), |
| 346 | deletePath, |
| 347 | ) |
| 348 | return new Set(setAsArray) |
| 349 | } |
| 350 | |
| 351 | if (Array.isArray(oldData)) { |
| 352 | const newData = [...oldData] |
| 353 | |
| 354 | if (deletePath.length === 1) { |
| 355 | return newData.filter((_, idx) => idx.toString() !== deletePath[0]) |
| 356 | } |
| 357 | |
| 358 | const [head, ...tail] = deletePath |
| 359 | |
| 360 | // @ts-expect-error |
| 361 | newData[head] = deleteNestedDataByPath(newData[head], tail) |
| 362 | |
| 363 | return newData |
| 364 | } |
| 365 | |
| 366 | if (isPlainObject(oldData)) { |
| 367 | const descriptors = Object.getOwnPropertyDescriptors(oldData) |
| 368 | const [head, ...tail] = deletePath |
| 369 | if (head === undefined) return oldData |
| 370 | if (tail.length === 0) { |
| 371 | delete descriptors[head] |
| 372 | } else { |
| 373 | const previous = Object.getOwnPropertyDescriptor(oldData, head) |
| 374 | if (!previous || !('value' in previous)) return oldData |
| 375 | descriptors[head] = { |
| 376 | ...previous, |
| 377 | value: deleteNestedDataByPath(previous.value, tail), |
| 378 | } |
| 379 | } |
| 380 | return Object.create(Object.getPrototypeOf(oldData), descriptors) |
no test coverage detected