Public
Script
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
export function convert(number, fromUnit, toUnit) {
const conversionRates = {
// Length
meter: 1,
kilometer: 1000,
centimeter: 0.01,
millimeter: 0.001,
inch: 0.0254,
foot: 0.3048,
yard: 0.9144,
mile: 1609.34,
// Mass
gram: 1,
kilogram: 1000,
ounce: 28.3495,
pound: 453.592,
};
if (!(fromUnit in conversionRates) || !(toUnit in conversionRates)) {
throw new Error("Invalid unit provided.");
}
const fromRate = conversionRates[fromUnit];
const toRate = conversionRates[toUnit];
const result = (number * fromRate) / toRate;
return result;
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
October 23, 2023