From 09d14230d5f3413f9d63f096ed5de23815ea4499 Mon Sep 17 00:00:00 2001 From: Alex Liu <39984251+Mini-ghost@users.noreply.github.com> Date: Sat, 17 Dec 2022 07:27:50 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=8F=8B=F0=9F=8F=BB=E2=80=8D=E2=99=80?= =?UTF-8?q?=EF=B8=8F=20reduced=20code=20with=20unset=20(#9575)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Beier (Bill) --- src/utils/unset.ts | 47 +++++++++++++++++----------------------------- 1 file changed, 17 insertions(+), 30 deletions(-) diff --git a/src/utils/unset.ts b/src/utils/unset.ts index 2f777db3ba3..766309b1d02 100644 --- a/src/utils/unset.ts +++ b/src/utils/unset.ts @@ -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;