Display Table of Food Orders in a Restaurant LeetCode solution in JavaScript

1
var displayTable = function (orders) {
2
var mapOrders = {};
3
var tables = [];
4
var dishes = [];
5
for (var i = 0; i < orders.length; i++) {
6
//if entry of table doesn't exist in mapOrders
7
if (mapOrders[orders[i][1]] == undefined) {
8
//conver table number to integer
9
var tableNo = Number(orders[i][1]);
10
mapOrders[tableNo] = {};
11
mapOrders[tableNo][orders[i][2]] = 1;
12
//if table number doesn't exist in table array, push it in the table array
13
if (!tables.includes(tableNo)) {
14
tables.push(tableNo);
15
}
16
//if dish doesn't exist in dishes array, push it in the dishes array
17
if (!dishes.includes(orders[i][2])) {
18
dishes.push(orders[i][2]);
19
}
20
} else {
21
//if entry of table exists in mapOrders
22
//conver table number to integer
23
var tableNo = Number(orders[i][1]);
24
var entry = mapOrders[tableNo];
25
//check if entry of dish exists in for that table in mapOrders
26
if (entry[orders[i][2]] == undefined) {
27
entry[orders[i][2]] = 1;
28
} else {
29
entry[orders[i][2]] = entry[orders[i][2]] + 1;
30
}
31
//if dish doesn't exist in dishes array, push it in the dishes array
32
if (!dishes.includes(orders[i][2])) {
33
dishes.push(orders[i][2]);
34
}
35
}
36
}
37
//sort tables and dishes
38
tables.sort(function (a, b) {
39
return a - b;
40
});
41
dishes.sort();
42
//append word "Table" with all dish names om row[0] of result
43
var res = [["Table"]];
44
for (var i = 0; i < dishes.length; i++) {
45
res[0].push(dishes[i]);
46
}
47
// read through map based on sorted table order
48
for (var i = 0; i < tables.length; i++) {
49
// append result in a temp array
50
var tmp = [];
51
//converting number to string using ""+
52
tmp.push("" + tables[i]);
53
for (var j = 0; j < dishes.length; j++) {
54
if (mapOrders[tables[i]][dishes[j]] == undefined) {
55
//if dish doesn't exist against that table then append "0" to the result for that dish
56
tmp.push("" + 0);
57
} else {
58
//if dish exists against that table then append value in mapOrders for that pair of (table,dish) to the result
59
tmp.push("" + mapOrders[tables[i]][dishes[j]]);
60
}
61
}
62
//append the temp array in result
63
res.push(tmp);
64
}
65
return res;
66
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0