-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreference.js
More file actions
39 lines (36 loc) · 2.13 KB
/
Copy pathreference.js
File metadata and controls
39 lines (36 loc) · 2.13 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
export const definitions = {
length: { metre: 1, kilometre: 1000, mile: 1609.344, inch: 0.0254, centimetre: 0.01, foot: 0.3048 },
mass: { kilogram: 1, pound: 0.45359237, ounce: 0.028349523125, gram: 0.001 },
speed: { metre_per_second: 1, kilometre_per_hour: 1 / 3.6, mile_per_hour: 0.44704, knot: 1852 / 3600 },
pressure: { pascal: 1, kilopascal: 1000, megapascal: 1000000, bar: 100000, psi: 6894.757293168, atmosphere: 101325 },
volume: { cubic_metre: 1, litre: 0.001, millilitre: 0.000001, us_liquid_gallon: 0.003785411784, us_fluid_ounce: 0.0000295735295625 },
energy: { joule: 1, calorie: 4.184, kilowatt_hour: 3600000 },
data_storage: { byte: 1, megabyte: 1000000, mebibyte: 1048576, gigabyte: 1000000000 },
time: { second: 1, hour: 3600, day: 86400, week: 604800 },
angle: { radian: 1, degree: Math.PI / 180 },
area: { square_metre: 1, acre: 4046.8564224 },
force: { newton: 1, pound_force: 4.4482216152605 },
power: { watt: 1, mechanical_horsepower: 745.699871582 }
};
function temperatureToKelvin(value, unit) {
if (unit === 'kelvin') return value;
if (unit === 'celsius') return value + 273.15;
if (unit === 'fahrenheit') return (value + 459.67) * 5 / 9;
throw new RangeError(`Unknown temperature unit: ${unit}`);
}
function temperatureFromKelvin(value, unit) {
if (unit === 'kelvin') return value;
if (unit === 'celsius') return value - 273.15;
if (unit === 'fahrenheit') return value * 9 / 5 - 459.67;
throw new RangeError(`Unknown temperature unit: ${unit}`);
}
export function convert(value, category, sourceUnit, targetUnit) {
if (!Number.isFinite(value)) throw new TypeError('value must be finite');
if (category === 'temperature') return temperatureFromKelvin(temperatureToKelvin(value, sourceUnit), targetUnit);
const categoryDefinitions = definitions[category];
if (!categoryDefinitions) throw new RangeError(`Unknown category: ${category}`);
const sourceFactor = categoryDefinitions[sourceUnit];
const targetFactor = categoryDefinitions[targetUnit];
if (!Number.isFinite(sourceFactor) || !Number.isFinite(targetFactor)) throw new RangeError('Unknown unit');
return value * sourceFactor / targetFactor;
}