Skip to content

Instantly share code, notes, and snippets.

@p7g
Created October 14, 2021 01:36
Show Gist options
  • Save p7g/a9ffc963db3f4fa22aac69d8c9e139c4 to your computer and use it in GitHub Desktop.
Save p7g/a9ffc963db3f4fa22aac69d8c9e139c4 to your computer and use it in GitHub Desktop.
the most robustest and fastest unit conversion library or your money back
type Quantity = symbol;
const Length: unique symbol = Symbol("Length quantity");
interface Unit<Q extends Quantity> {
quantity: Q;
factor: number;
}
export const Millimeter: Unit<typeof Length> = {
quantity: Length,
factor: 1,
};
export const Meter: Unit<typeof Length> = {
quantity: Length,
factor: 1000,
};
export const Inch: Unit<typeof Length> = {
quantity: Length,
factor: 25.4,
};
export const Foot: Unit<typeof Length> = {
quantity: Length,
factor: Inch.factor * 12,
};
const Volume: unique symbol = Symbol("Volume quantity");
export const Milliliter: Unit<typeof Volume> = {
quantity: Volume,
factor: 1,
};
export const Deciliter: Unit<typeof Volume> = {
quantity: Volume,
factor: 100,
};
export const Liter: Unit<typeof Volume> = {
quantity: Volume,
factor: 1000,
};
export const InchCubed: Unit<typeof Volume> = {
quantity: Volume,
factor: 16.387,
};
const Time: unique symbol = Symbol("Time quantity");
export const Second: Unit<typeof Time> = {
quantity: Time,
factor: 1000,
};
export const Minute: Unit<typeof Time> = {
quantity: Time,
factor: Second.factor * 60,
};
export const Hour: Unit<typeof Time> = {
quantity: Time,
factor: Minute.factor * 60,
};
export function convert<Q extends Quantity>(value: number, from: Unit<Q>, to: Unit<Q>): number {
const ratio = from.factor / to.factor;
return value * ratio;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment