forked from wdi-sg/temperature_converter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
executable file
·65 lines (53 loc) · 2.09 KB
/
script.js
File metadata and controls
executable file
·65 lines (53 loc) · 2.09 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
// define each conversion in a function
function FtoC(temp) {
return (temp - 32) * 1.8;
}
function FtoK(temp) {
return ((temp - 32) * 5/9) + 273.15;
}
function CtoF(temp) {
return (temp / 1.8) + 32;
}
function CtoK(temp) {
return temp + 273.15;
}
function KtoC(temp) {
return temp - 273.15;
}
function KtoF(temp) {
return (temp - 273.15) * 1.8 + 32;
}
function convert(temp, unit) {
// Use object key-value to store and access the user-submitted and converted temperatures.
var temperaturesList = {};
if (unit === "Fahrenheit") {
temperaturesList[unit] = temp;
temperaturesList["Celsius"] = FtoC(temp);
temperaturesList["Kelvin"] = FtoK(temp);
} else if (unit === "Celsius") {
temperaturesList[unit] = temp;
temperaturesList["Kelvin"] = CtoK(temp);
temperaturesList["Fahrenheit"] = CtoF(temp);
} else if (unit === "Kelvin") {
temperaturesList[unit] = temp;
temperaturesList["Celsius"] = KtoC(temp);
temperaturesList["Fahrenheit"] = KtoF(temp);
} else {
alert("Invalid Unit!");
return;
}
return temperaturesList;
}
// Use a for or while loop to print out the conversion results for each temperature.
do {
// Prompt the user for a starting temperature. This should be a numerical value that represents degrees.
var temperatureInput = parseFloat(prompt("Enter a temperature"));
// Prompt the user for a starting temperatureUnit. This will represent either Fahrenheit, Celsius, or Kelvin.
var temperatureUnit = prompt("Enter a temperature unit in Fahrenheit, Celsius, or Kelvin");
var temperatures = convert(temperatureInput, temperatureUnit);
var keys = Object.keys(temperatures);
if (temperatures) {
alert(temperatures[keys[0]].toFixed(2) + " " + keys[0] + " is " + temperatures[keys[1]].toFixed(2) + " " + keys[1] + " or " + temperatures[keys[2]].toFixed(2) + " " + keys[2] + ".");
}
// Using loops, create an interface that continues to ask the user for temp conversions until the user requests to stop.
} while (confirm("Continue to convert?"));