Skip to content

Commit

Permalink
Deep object copy of the initial config
Browse files Browse the repository at this point in the history
  • Loading branch information
Mgonzalez06 committed Jul 10, 2024
1 parent d951b03 commit 863289f
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
};
}

Expand Down Expand Up @@ -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<T>(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;
}
}

0 comments on commit 863289f

Please sign in to comment.