2021-11-14 10:55:39 +01:00
|
|
|
import { IUnit, TFactor, TUnit } from '@/types/units'
|
|
|
|
|
|
|
|
export const units: Record<string, IUnit> = {
|
|
|
|
ft: {
|
|
|
|
unit: 'ft',
|
|
|
|
system: 'imperial',
|
|
|
|
multiplier: 1,
|
2021-11-14 12:12:21 +01:00
|
|
|
defaultTarget: 'm',
|
2021-11-14 10:55:39 +01:00
|
|
|
},
|
|
|
|
mi: {
|
|
|
|
unit: 'mi',
|
|
|
|
system: 'imperial',
|
|
|
|
multiplier: 5280,
|
2021-11-14 12:12:21 +01:00
|
|
|
defaultTarget: 'km',
|
2021-11-14 10:55:39 +01:00
|
|
|
},
|
|
|
|
m: {
|
|
|
|
unit: 'm',
|
|
|
|
system: 'metric',
|
|
|
|
multiplier: 1,
|
2021-11-14 12:12:21 +01:00
|
|
|
defaultTarget: 'ft',
|
2021-11-14 10:55:39 +01:00
|
|
|
},
|
|
|
|
km: {
|
|
|
|
unit: 'm',
|
|
|
|
system: 'metric',
|
|
|
|
multiplier: 1000,
|
2021-11-14 12:12:21 +01:00
|
|
|
defaultTarget: 'mi',
|
2021-11-14 10:55:39 +01:00
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
const factors: TFactor = {
|
|
|
|
metric: {
|
|
|
|
imperial: 3.280839895,
|
|
|
|
metric: 1,
|
|
|
|
},
|
|
|
|
imperial: {
|
|
|
|
metric: 1 / 3.280839895,
|
|
|
|
imperial: 1,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
export const convertDistance = (
|
|
|
|
distance: number,
|
|
|
|
from: TUnit,
|
|
|
|
to: TUnit,
|
|
|
|
digits: number | null = 3
|
|
|
|
): number => {
|
|
|
|
const unitFrom = units[from]
|
|
|
|
const unitTo = units[to]
|
|
|
|
const convertedDistance =
|
|
|
|
(distance * unitFrom.multiplier * factors[unitFrom.system][unitTo.system]) /
|
|
|
|
unitTo.multiplier
|
|
|
|
if (digits !== null) {
|
|
|
|
return parseFloat(convertedDistance.toFixed(digits))
|
|
|
|
}
|
|
|
|
return convertedDistance
|
|
|
|
}
|