Skip to content
Open
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 51 additions & 3 deletions src/herbivoresAndCarnivores.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,63 @@
'use strict';

class Animal {
// write your code here
static alive = [];
static emptyslots = [];
constructor(name, health = 100) {
this.name = name;
this._health = health;
this.isalive = true;

if (Animal.emptyslots.length === 0) {
this.index = Animal.alive.push(this) - 1;
} else {
const index = Animal.emptyslots.pop();

this.index = index;
Animal.alive[index] = this;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Logic with indexes looks difficult; try to simplify it

}

get health() {
return this._health;
}

set health(value) {
this._health = value;

if (this._health <= 0) {
this.isalive = false;
this.die();
}
}
getHeart(value) {
this.health -= value;
}
die() {
Animal.alive[this.index] = null;
Animal.emptyslots.push(this.index);
}
}

class Herbivore extends Animal {
// write your code here
constructor(name, health) {
super(name, health);
this.hidden = false;
}

hide() {
this.hidden = true;
}
}

class Carnivore extends Animal {
// write your code here
bite(animal) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Override instruction requires checking instanceof Herbivore, not instanceof Carnivore. The condition should be if (!(animal instanceof Herbivore) || animal.hidden) or equivalent to satisfy the override requirement.

if (animal instanceof Carnivore || animal.hidden) {
return;
}

animal.getHeart(50);
}
}

module.exports = {
Expand Down
Loading