Skip to content

Commit 67715a5

Browse files
committed
second eterations
1 parent 23b05d4 commit 67715a5

1 file changed

Lines changed: 15 additions & 2 deletions

File tree

src/herbivoresAndCarnivores.js

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,20 @@
22

33
class Animal {
44
static alive = [];
5+
static emptyslots = [];
56
constructor(name, health = 100) {
67
this.name = name;
78
this._health = health;
89
this.isalive = true;
9-
Animal.alive.push(this);
10+
11+
if (Animal.emptyslots.length === 0) {
12+
this.index = Animal.alive.push(this) - 1;
13+
} else {
14+
const index = Animal.emptyslots.pop();
15+
16+
this.index = index;
17+
Animal.alive[index] = this;
18+
}
1019
}
1120

1221
get health() {
@@ -18,12 +27,16 @@ class Animal {
1827

1928
if (this._health <= 0) {
2029
this.isalive = false;
21-
Animal.alive = Animal.alive.filter((animal) => animal.isalive);
30+
this.die();
2231
}
2332
}
2433
getHeart(value) {
2534
this.health -= value;
2635
}
36+
die() {
37+
Animal.alive[this.index] = null;
38+
Animal.emptyslots.push(this.index);
39+
}
2740
}
2841

2942
class Herbivore extends Animal {

0 commit comments

Comments
 (0)