From 863289fc7410a46d1f12efe0b698a1e19516308c Mon Sep 17 00:00:00 2001 From: Mgonzalez06 Date: Wed, 10 Jul 2024 10:42:28 -0600 Subject: [PATCH] Deep object copy of the initial config --- src/index.ts | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/src/index.ts b/src/index.ts index 0437f7d..13f9095 100644 --- a/src/index.ts +++ b/src/index.ts @@ -39,7 +39,7 @@ export class Validation implements FormValidation { if (typeof config !== 'object') throw new Error('Config must be an object.'); this.config = { ...this.config, - ...config, + ...this.cloneDeep(config), }; } @@ -594,4 +594,31 @@ export class Validation implements FormValidation { this.config.fields[fieldName] = { ...config }; this.setupFieldConfig(fieldName, config.rules, config.messages); } + + + /** + * Clones an object deeply. + * We need this method to clone the configuration object and allow us to use the same configuration object in different instances. + * @param {T} obj - Object to clone. + * @returns {T} - Cloned object. + */ + cloneDeep(obj: T): T { + if (obj === null || typeof obj !== "object") { + return obj; + } + + if (Array.isArray(obj)) { + const copy: any = []; + obj.forEach((elem, index) => { + copy[index] = this.cloneDeep(elem); + }); + return copy; + } + + const copy: any = {}; + Object.keys(obj).forEach((key) => { + copy[key] = this.cloneDeep((obj as any)[key]); + }); + return copy; + } }