@thangk/easythemer
Version:
Easily generate shades from a colour palette for use in your app
77 lines (61 loc) • 1.94 kB
text/typescript
/**
* @param {T} object1
* @param {T} object2
* @getters getResult(), hasErrors(), getErrorsList()
* @result boolean
* @description
* This class is used to validate if two objects have the same properties by checking if they object with the most properties has all the properties of the object with the least properties.
*/
export default class ValidateSameObjectType<T extends Object> {
private result: boolean = false;
private errors: boolean = false;
private errmsg: string[] = [];
constructor(object1: T, object2: T) {
this.result = this.haveCommonProperties(object1, object2);
}
get getResult() {
return this.result;
}
get hasErrors() {
return this.errors;
}
get getErrorsList() {
return this.errmsg;
}
private showErrors() {
this.errmsg.forEach((msg) => {
console.log(msg);
});
}
private addError(msg: string) {
this.errmsg.push(msg);
}
private setErrorState() {
this.errors = true;
}
private haveCommonProperties(object1: T, object2: T) {
let currentKeysCount = 0;
const { minKeyLen, minKeyObj, maxKeyObj } = this.getMinLenObj(object1, object2);
for (const [key, value] of Object.entries(minKeyObj)) {
if (key in maxKeyObj) {
currentKeysCount++;
}
}
if (currentKeysCount === minKeyLen) return true;
this.addError("Object keys size are not equal.");
this.setErrorState();
return false;
}
private getMinLenObj(object1: T, object2: T) {
const keysLen1 = Object.keys(object1).length;
const keysLen2 = Object.keys(object2).length;
const minKeyLen = keysLen1 < keysLen2 ? keysLen1 : keysLen2;
const minKeyObj = keysLen1 < keysLen2 ? object1 : object2;
const maxKeyObj = keysLen1 < keysLen2 ? object2 : object1;
return {
minKeyLen,
minKeyObj,
maxKeyObj,
};
}
}