Skip to content
Open
Changes from all 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
84 changes: 81 additions & 3 deletions src/herbivoresAndCarnivores.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,93 @@
'use strict';

class Animal {
// write your code here
/**
static createAliveAnimalList() {
const alive = [];
const emptyslots = [];

const list = alive;

list.add = (animal) => {
if (emptyslots.length === 0) {
animal.index = alive.push(animal) - 1;
} else {
const index = emptyslots.pop();

animal.index = index;
alive[index] = animal;
}
};

list.remove = (animal) => {
alive[animal.index] = null;
emptyslots.push(animal.index);
};

return list;
}

static alive = Animal.createAliveAnimalList();
*/
Comment on lines +4 to +31

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

remove comments


static alive = [];
static #emptyslots = [];

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

why such a variable name?


constructor(name, health = 100) {
this.name = name;
this._health = health;
this.addToAlive();
}

addToAlive() {
if (Animal.#emptyslots.length > 0) {
this.index = Animal.#emptyslots.pop();
Animal.alive[this.index] = this;

return;
}

this.index = Animal.alive.length;
Animal.alive.push(this);
}
get health() {
return this._health;
}
set health(value) {
this._health = value;

if (this._health <= 0) {
this.die();
}
}
takeDamage(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 Herbivore) || animal.hidden) {
return;
}

animal.takeDamage(50);
}
}

module.exports = {
Expand Down
Loading