forked from bethrobson/Head-First-JavaScript-Programming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcola.html
More file actions
89 lines (76 loc) · 2.18 KB
/
cola.html
File metadata and controls
89 lines (76 loc) · 2.18 KB
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
<!doctype html>
<html lang="en">
<head>
<title>Webville Cola</title>
<meta charset="utf-8">
<script>
var products = [ { name: "Grapefruit", calories: 170, color: "red", sold: 8200 },
{ name: "Orange", calories: 160, color: "orange", sold: 12101 },
{ name: "Cola", calories: 210, color: "caramel", sold: 25412 },
{ name: "Diet Cola", calories: 0, color: "caramel", sold: 43922 },
{ name: "Lemon", calories: 200, color: "clear", sold: 14983 },
{ name: "Raspberry", calories: 180, color: "pink", sold: 9427 },
{ name: "Root Beer", calories: 200, color: "caramel", sold: 9909 },
{ name: "Water", calories: 0, color: "clear", sold: 62123 }
];
// sort and display the scores
console.log("\n------- sorting by sold -------");
products.sort(compareSold);
printProducts(products);
console.log("\n------- sorting by name -------");
products.sort(compareName);
printProducts(products);
console.log("\n------- sorting by calories -------");
products.sort(compareCalories);
printProducts(products);
console.log("\n------- sorting by color -------");
products.sort(compareColor);
printProducts(products);
function compareName(colaA, colaB) {
if (colaA.name > colaB.name) {
return 1;
} else if (colaA.name === colaB.name) {
return 0;
} else {
return -1;
}
}
function compareCalories(colaA, colaB) {
if (colaA.calories > colaB.calories) {
return 1;
} else if (colaA.calories === colaB.calories) {
return 0;
} else {
return -1;
}
}
function compareColor(colaA, colaB) {
if (colaA.color > colaB.color) {
return 1;
} else if (colaA.color === colaB.color) {
return 0;
} else {
return -1;
}
}
function compareSold(colaA, colaB) {
if (colaA.sold > colaB.sold) {
return 1;
} else if (colaA.sold === colaB.sold) {
return 0;
} else {
return -1;
}
}
function printProducts(products) {
for (var i = 0; i < products.length; i++) {
console.log("Name: " + products[i].name +
", Calories: " + products[i].calories +
", Color: " + products[i].color +
", Sold: " + products[i].sold);
}
}
</script>
</head>
<body> </body>
</html>