Create a queue-like animal shelter in JavaScript

Here is a way to implement a data structure that holds only dogs or cats and only allows people to adopt the oldest (FIFO) of any one type. Operations include enqueue, dequeueAny, dequeueDog and dequeueCat.

AnimalShelterTry in REPL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
function AnimalShelter() {
this.size = 0;
this.first = this.last = null;
}
function Node(data) {
this.data = data;
this.next = null;
}
AnimalShelter.prototype.enqueue = function(data) {
const node = new Node(data);
if (this.last) this.last.next = node;
this.last = node;
if (!this.first) this.first = this.last;
this.size++;
return node; // returning for the sake of testing
};
AnimalShelter.prototype.dequeueAny = function() {
if (!this.first) return;
const data = this.first.data;
this.first = this.first.next;
if (!this.first) this.last = null;
this.size = Math.max(0, this.size - 1);
return data;
};
AnimalShelter.prototype.dequeueDog = function() {
let prev = current = this.first;
let next = current ? current.next : null;
let dog;
while (current) {
if (current.data === 'dog') {
// Only one node in list
if (this.first === current && next === null) {
this.first = this.last = null;
} else if (next === null && prev) {
// Removing the last node
this.last = prev;
}
dog = current.data;
prev.next = next;
this.size--;
break;
}
prev = current;
current = next;
next = current ? current.next : null;
}
return dog;
};
AnimalShelter.prototype.dequeueCat = function() {
let prev = current = this.first;
let next = current ? current.next : null;
let cat;
while (current) {
if (current.data === 'cat') {
// Only one node in list
if (this.first === current && next === null) {
this.first = this.last = null;
} else if (next === null && prev) {
// Removing the last node
this.last = prev;
}
cat = current.data;
prev.next = next;
this.size--;
break;
}
prev = current;
current = next;
next = current ? current.next : null;
}
return cat;
};
AnimalShelter.prototype.peek = function() {
if (!this.first) return;
return this.first.data;
};
AnimalShelter.prototype.isEmpty = function() {
return this.size === 0 && !this.first;
};
AnimalShelter.prototype.getSize = function() {
return this.size;
}

Tests can be found at REPL.it