Design a Food Rating System LeetCode solution in JavaScript

1
var FoodRatings = function (foods, cuisines, ratings) {
2
(this.heaps = {}), (this.foods = {});
3
let n = foods.length;
4
for (let i = 0; i < n; i++) {
5
let food = foods[i],
6
cuisine = cuisines[i],
7
rating = ratings[i];
8
if (!this.heaps[cuisine])
9
this.heaps[cuisine] = new PriorityQueue((a, b) => {
10
// [food, rating]
11
return a[1] === b[1] ? a[0].localeCompare(b[0]) : b[1] - a[1];
12
});
13
this.heaps[cuisine].add([food, rating]);
14
this.foods[food] = { cuisine, rating };
15
}
16
};
17

18
FoodRatings.prototype.changeRating = function (food, newRating) {
19
this.foods[food].rating = newRating;
20
let { cuisine } = this.foods[food];
21
this.heaps[cuisine].add([food, newRating]);
22
};
23

24
FoodRatings.prototype.highestRated = function (cuisine) {
25
let heap = this.heaps[cuisine];
26
while (this.foods[heap.top()[0]].rating !== heap.top()[1]) {
27
heap.remove();
28
}
29
return heap.top()[0];
30
};
31

32
class PriorityQueue {
33
constructor(comparator = (a, b) => a - b) {
34
this.values = [];
35
this.comparator = comparator;
36
this.size = 0;
37
}
38
add(val) {
39
this.size++;
40
this.values.push(val);
41
let idx = this.size - 1,
42
parentIdx = Math.floor((idx - 1) / 2);
43
while (
44
parentIdx >= 0 &&
45
this.comparator(this.values[parentIdx], this.values[idx]) > 0
46
) {
47
[this.values[parentIdx], this.values[idx]] = [
48
this.values[idx],
49
this.values[parentIdx],
50
];
51
idx = parentIdx;
52
parentIdx = Math.floor((idx - 1) / 2);
53
}
54
}
55
remove() {
56
if (this.size === 0) return -1;
57
this.size--;
58
if (this.size === 0) return this.values.pop();
59
let removedVal = this.values[0];
60
this.values[0] = this.values.pop();
61
let idx = 0;
62
while (idx < this.size && idx < Math.floor(this.size / 2)) {
63
let leftIdx = idx * 2 + 1,
64
rightIdx = idx * 2 + 2;
65
if (rightIdx === this.size) {
66
if (this.comparator(this.values[leftIdx], this.values[idx]) > 0) break;
67
[this.values[leftIdx], this.values[idx]] = [
68
this.values[idx],
69
this.values[leftIdx],
70
];
71
idx = leftIdx;
72
} else if (
73
this.comparator(this.values[leftIdx], this.values[idx]) < 0 ||
74
this.comparator(this.values[rightIdx], this.values[idx]) < 0
75
) {
76
if (this.comparator(this.values[leftIdx], this.values[rightIdx]) <= 0) {
77
[this.values[leftIdx], this.values[idx]] = [
78
this.values[idx],
79
this.values[leftIdx],
80
];
81
idx = leftIdx;
82
} else {
83
[this.values[rightIdx], this.values[idx]] = [
84
this.values[idx],
85
this.values[rightIdx],
86
];
87
idx = rightIdx;
88
}
89
} else {
90
break;
91
}
92
}
93
return removedVal;
94
}
95
top() {
96
return this.values[0];
97
}
98
isEmpty() {
99
return this.size === 0;
100
}
101
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0