From 5754c4748390dca8f7e51e9141793446f5bb50df Mon Sep 17 00:00:00 2001 From: "Beier (Bill)" Date: Tue, 21 May 2024 08:41:30 +1000 Subject: [PATCH] fix: move back to in-build set and remove lodash.set (#685) --- src/toNestErrors.ts | 48 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/src/toNestErrors.ts b/src/toNestErrors.ts index 9eb102aa..908db46f 100644 --- a/src/toNestErrors.ts +++ b/src/toNestErrors.ts @@ -6,9 +6,55 @@ import { FieldValues, InternalFieldName, } from 'react-hook-form'; -import set from 'lodash.set'; import { validateFieldsNatively } from './validateFieldsNatively'; +export const isDateObject = (value: unknown): value is Date => value instanceof Date; + +export const isNullOrUndefined = (value: unknown): value is null | undefined => value == null; + +export const isObjectType = (value: unknown): value is object => + typeof value === 'object'; + +export const isObject = (value: unknown): value is T => + !isNullOrUndefined(value) && + !Array.isArray(value) && + isObjectType(value) && + !isDateObject(value); + +export const isKey = (value: string) => /^\w*$/.test(value); + +const compact = (value: TValue[]) => + Array.isArray(value) ? value.filter(Boolean) : []; + +const stringToPath = (input: string): string[] => + compact(input.replace(/["|']|\]/g, '').split(/\.|\[/)); + +const set = (object: FieldValues, path: string, value?: unknown) => { + let index = -1; + const tempPath = isKey(path) ? [path] : stringToPath(path); + const length = tempPath.length; + const lastIndex = length - 1; + + while (++index < length) { + const key = tempPath[index]; + let newValue = value; + + if (index !== lastIndex) { + const objValue = object[key]; + newValue = + isObject(objValue) || Array.isArray(objValue) + ? objValue + : !isNaN(+tempPath[index + 1]) + ? [] + : {}; + } + object[key] = newValue; + object = object[key]; + } + return object; +}; + + export const toNestErrors = ( errors: FieldErrors, options: ResolverOptions,