|
| 1 | +import { AvlTree } from "https://esm.sh/@datastructures-js/[email protected]/?dts"; |
| 2 | + |
| 3 | +class FoodRatings { |
| 4 | + #cuisineToTree = new Map<string, AvlTree<string>>(); |
| 5 | + #foodToTree = new Map<string, AvlTree<string>>(); |
| 6 | + #foodToRating = new Map<string, number>(); |
| 7 | + constructor(foods: string[], cuisines: string[], ratings: number[]) { |
| 8 | + for (const [index, food] of foods.entries()) { |
| 9 | + const cuisine = cuisines[index]; |
| 10 | + const rating = ratings[index]; |
| 11 | + this.#foodToRating.set(food, rating); |
| 12 | + const tree = this.#cuisineToTree.get(cuisine) ?? |
| 13 | + new AvlTree((a, b) => { |
| 14 | + const ra = this.#foodToRating.get(a) ?? 0; |
| 15 | + const rb = this.#foodToRating.get(b) ?? 0; |
| 16 | + return ra === rb ? a.localeCompare(b) : -ra + rb; |
| 17 | + }); |
| 18 | + |
| 19 | + this.#cuisineToTree.set(cuisine, tree); |
| 20 | + this.#foodToTree.set(food, tree); |
| 21 | + |
| 22 | + tree.insert(food); |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + changeRating(food: string, newRating: number): void { |
| 27 | + const tree = this.#foodToTree.get(food); |
| 28 | + if (!tree) throw Error("not found"); |
| 29 | + |
| 30 | + tree.remove(food); |
| 31 | + this.#foodToRating.set(food, newRating); |
| 32 | + tree.insert(food); |
| 33 | + } |
| 34 | + |
| 35 | + highestRated(cuisine: string): string { |
| 36 | + return this.#cuisineToTree.get(cuisine)?.min()?.getValue() ?? ""; |
| 37 | + } |
| 38 | +} |
| 39 | +export default FoodRatings; |
0 commit comments