Skip to content

Commit

Permalink
fix: move back to in-build set and remove lodash.set (#685)
Browse files Browse the repository at this point in the history
  • Loading branch information
bluebill1049 authored May 20, 2024
1 parent bdc1f1f commit 5754c47
Showing 1 changed file with 47 additions and 1 deletion.
48 changes: 47 additions & 1 deletion src/toNestErrors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = <T extends object>(value: unknown): value is T =>
!isNullOrUndefined(value) &&
!Array.isArray(value) &&
isObjectType(value) &&
!isDateObject(value);

export const isKey = (value: string) => /^\w*$/.test(value);

const compact = <TValue>(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 = <TFieldValues extends FieldValues>(
errors: FieldErrors,
options: ResolverOptions<TFieldValues>,
Expand Down

0 comments on commit 5754c47

Please sign in to comment.