I am following this article.
/**
* The group name should contain a minimum of 3 and a maximum of 12 capital letters.
* No space, number, or special characters are allowed
*/
console.clear();
class Group {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
getLength() {
return this.name.length;
}
add(name) {}
remove(name) {}
toString() {
return `Group: ${this.name}`;
}
}
class DefaultGroup {
constructor(group) {
this.origin = group;
}
getName() {
return this.origin.getName();
}
getLength() {
return this.origin.getLength();
}
validate() {
return true;
}
}
class OnlyUpCaseGroup extends DefaultGroup {
constructor(origin) {
super(origin);
if (!this.validate()) {
alert('Invalid group name ' + this.getName());
throw Error('Invalid group name');
}
}
validate() {
let REGEX_UP_CASE = /^[A-Z]*$/g;
return super.validate() && REGEX_UP_CASE.test(this.getName());
}
toString() {
return `Group: ${this.getName()}`;
}
}
class ValidLengthGroup extends DefaultGroup {
constructor(origin) {
super(origin);
if (!this.validate()) {
alert('Length must be between 3 and 12');
throw Error('Invalid group name');
}
}
validate() {
let len = this.getLength();
return super.validate() && len >= 3 && len <= 12;
}
toString() {
return `Group: ${this.getName()}`;
}
}
let g = new Group('FOOOBAAAR');
//console.log(new OnlyUpCaseGroup(new Group('vivek')));
//console.log(new OnlyUpCaseGroup(new DefaultGroup(g)));
//console.log(new ValidLengthGroup(new DefaultGroup(g)));
console.log(new ValidLengthGroup(new OnlyUpCaseGroup(new DefaultGroup(g))));
Questions:
- I need to know if I am following the pattern properly?
- Can I do same with less verbose code?
Note:
Maintainability and flexibility is prime here. Keep in mind that there can be more validations.