-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathtempconv.js
More file actions
113 lines (109 loc) · 2.44 KB
/
tempconv.js
File metadata and controls
113 lines (109 loc) · 2.44 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
'use strict';
//
// tempconv
//
// A function that converts a temperature between formats
//
// Usage:
// {
// temperature: <float|int>
// format: <C|F|K>
// target: <C|F|K>
// }
//
// Output:
// {
// temperature: <float|int>
// target: <C|F|K>
// }
// Formats is a 2d-map, in which the outer dimension is the source and the inner dimension is the target format.
const conversions = {
"C": {
"K": (temp) => {
return temp + 273.15
},
"F": (temp) => {
return temp * (9 / 5) + 32
}
},
"K": {
"C": (temp) => {
return temp - 273.15
},
"F": (temp) => {
return temp * (9 / 5) - 459.67
}
},
"F": {
"C": (temp) => {
return (temp - 32) * (5 / 9)
},
"K": (temp) => {
return (temp + 459.67) * (5 / 9)
},
},
};
function convert(temp, format, target) {
if (format === target) {
return temp
}
const src = conversions[format];
if (!src) {
throw new Error(`unknown temperature format '${format}'`)
}
const conv = src[target];
if (!conv) {
throw new Error(`unknown temperature target '${target}'`)
}
return conv(temp)
}
module.exports = async function (context) {
const b = context.request.body;
console.log("body", b);
if (!b) {
return {
status: 400,
body: 'missing body',
};
}
if (!b.temperature) {
return {
status: 400,
body: 'missing temperature',
};
}
if (!b.format) {
return {
status: 400,
body: 'missing temperature format',
};
}
if (!b.target) {
return {
status: 400,
body: 'missing temperature target',
};
}
const temperature = parseFloat(b.temperature);
const format = b.format.toUpperCase().trim();
const target = b.target.toUpperCase().trim();
try {
const converted = convert(temperature, format, target);
console.log(`result: ${converted}`);
return {
status: 200,
body: {
temperature: Math.round(converted),
format: target
},
headers: {
'Content-Type': 'application/json'
}
}
} catch (e) {
return {
status: 400,
body: e.message
}
}
};