Skip to content

Commit

Permalink
πŸ‹πŸ»β€β™€οΈ reduced code with unset (#9575)
Browse files Browse the repository at this point in the history
Co-authored-by: Beier (Bill) <bluebill1049@hotmail.com>
  • Loading branch information
Mini-ghost and bluebill1049 committed Dec 16, 2022
1 parent 52f5f95 commit 09d1423
Showing 1 changed file with 17 additions and 30 deletions.
47 changes: 17 additions & 30 deletions src/utils/unset.ts
Expand Up @@ -24,41 +24,28 @@ function isEmptyArray(obj: unknown[]) {
return true;
}

export default function unset(object: any, path: string) {
const updatePath = isKey(path) ? [path] : stringToPath(path);
const childObject =
updatePath.length == 1 ? object : baseGet(object, updatePath);
const key = updatePath[updatePath.length - 1];
let previousObjRef;
export default function unset(object: any, path: string | (string | number)[]) {
const paths = Array.isArray(path)
? path
: isKey(path)
? [path]
: stringToPath(path);

const childObject = paths.length === 1 ? object : baseGet(object, paths);

const index = paths.length - 1;
const key = paths[index];

if (childObject) {
delete childObject[key];
}

for (let k = 0; k < updatePath.slice(0, -1).length; k++) {
let index = -1;
let objectRef;
const currentPaths = updatePath.slice(0, -(k + 1));
const currentPathsLength = currentPaths.length - 1;

if (k > 0) {
previousObjRef = object;
}

while (++index < currentPaths.length) {
const item = currentPaths[index];
objectRef = objectRef ? objectRef[item] : object[item];

if (
currentPathsLength === index &&
((isObject(objectRef) && isEmptyObject(objectRef)) ||
(Array.isArray(objectRef) && isEmptyArray(objectRef)))
) {
previousObjRef ? delete previousObjRef[item] : delete object[item];
}

previousObjRef = objectRef;
}
if (
index !== 0 &&
((isObject(childObject) && isEmptyObject(childObject)) ||
(Array.isArray(childObject) && isEmptyArray(childObject)))
) {
unset(object, paths.slice(0, -1));
}

return object;
Expand Down

0 comments on commit 09d1423

Please sign in to comment.