Skip to content

Commit f6ff75c

Browse files
committed
Tried to make the logic simpler while maintaining O(1) time complexity
1 parent 67715a5 commit f6ff75c

1 file changed

Lines changed: 45 additions & 15 deletions

File tree

src/herbivoresAndCarnivores.js

Lines changed: 45 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,71 @@
11
'use strict';
22

33
class Animal {
4+
/**
5+
static createAliveAnimalList() {
6+
const alive = [];
7+
const emptyslots = [];
8+
9+
const list = alive;
10+
11+
list.add = (animal) => {
12+
if (emptyslots.length === 0) {
13+
animal.index = alive.push(animal) - 1;
14+
} else {
15+
const index = emptyslots.pop();
16+
17+
animal.index = index;
18+
alive[index] = animal;
19+
}
20+
};
21+
22+
list.remove = (animal) => {
23+
alive[animal.index] = null;
24+
emptyslots.push(animal.index);
25+
};
26+
27+
return list;
28+
}
29+
30+
static alive = Animal.createAliveAnimalList();
31+
*/
32+
433
static alive = [];
5-
static emptyslots = [];
34+
static #emptyslots = [];
35+
636
constructor(name, health = 100) {
737
this.name = name;
838
this._health = health;
9-
this.isalive = true;
39+
this.addToAlive();
40+
}
1041

11-
if (Animal.emptyslots.length === 0) {
12-
this.index = Animal.alive.push(this) - 1;
13-
} else {
14-
const index = Animal.emptyslots.pop();
42+
addToAlive() {
43+
if (Animal.#emptyslots.length > 0) {
44+
this.index = Animal.#emptyslots.pop();
45+
Animal.alive[this.index] = this;
1546

16-
this.index = index;
17-
Animal.alive[index] = this;
47+
return;
1848
}
19-
}
2049

50+
this.index = Animal.alive.length;
51+
Animal.alive.push(this);
52+
}
2153
get health() {
2254
return this._health;
2355
}
24-
2556
set health(value) {
2657
this._health = value;
2758

2859
if (this._health <= 0) {
29-
this.isalive = false;
3060
this.die();
3161
}
3262
}
33-
getHeart(value) {
63+
takeDamage(value) {
3464
this.health -= value;
3565
}
3666
die() {
3767
Animal.alive[this.index] = null;
38-
Animal.emptyslots.push(this.index);
68+
Animal.#emptyslots.push(this.index);
3969
}
4070
}
4171

@@ -52,11 +82,11 @@ class Herbivore extends Animal {
5282

5383
class Carnivore extends Animal {
5484
bite(animal) {
55-
if (animal instanceof Carnivore || animal.hidden) {
85+
if (!(animal instanceof Herbivore) || animal.hidden) {
5686
return;
5787
}
5888

59-
animal.getHeart(50);
89+
animal.takeDamage(50);
6090
}
6191
}
6292

0 commit comments

Comments
 (0)