Skip to content

Instantly share code, notes, and snippets.

@Caballerog
Created May 31, 2022 09:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Caballerog/53af869510643935076a83e658542ed1 to your computer and use it in GitHub Desktop.
Save Caballerog/53af869510643935076a83e658542ed1 to your computer and use it in GitHub Desktop.
class Character {
private _power: number;
private _name: string;
private _type: string; // Heroe, Villain or Human
constructor(name:string, power: number = 0, type: string ){
this._name = name;
this._power = power;
this._type = type;
}
get power(): number {
return this._power;
};
get name(): string {
return this._name;
}
get type(): string {
return this._type;
}
calculateFightPower(): number{
let result = 0;
if(this.type === 'Heroe') {
result += this._power * 2;
}
if(this.type === 'Villain'){
result += this._power + 100;
}
if(this.type === 'Human') {
result += this._power + 10;
}
// OCP Violated: if We need a new character's type.
return result;
}
}
class CharacterService {
characters: Character[] = [
new Character("Mario", 100, 'Heroe'),
new Character("Koopa", 85, 'Villain'),
new Character("Carlos", 30, 'Human'),
];
constructor() {
const power = this.calculatePowerTeam(this.characters);
console.log(`The power of the team is ${power}`);
}
calculatePowerTeam(characters: Character[]){
let power = 0;
for (const character of characters) {
power += character.calculateFightPower();
}
return power;
}
}
new CharacterService();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment