PliWould/lib/dimensions.ts

52 lines
1.6 KiB
TypeScript

import convert from "convert";
import { Length } from "convert";
export type length_t = {
l: number; u: Length;
};
export type area_t = length_t & {
w: number;
};
export type dimensions_t = area_t | length_t;
export type product_type_t = "area" | "length";
export const isArea = (d: dimensions_t) => ("width" in d);
export const isLength = (d: dimensions_t) => (!("width" in d));
export const dimensionType = (d: dimensions_t) => isArea(d) ? "area" : "length"; export function matchDimensions(d1: dimensions_t, d2: dimensions_t) {
if (!(
(isArea(d1) && isArea(d2)) ||
(isLength(d1) && isLength(d2))
)) {
throw new Error(`Dimension mismatch: ${JSON.stringify(d1)} / ${JSON.stringify(d1)}`);
}
return {
l: convert(d1.l, d1.u).to(d2.u),
u: d2.u,
...(
"w" in d1 ?
{ w: convert(d1.w, d1.u).to(d2.u), }
: {}
)
};
}
/**
* Gets the total length of a carpet roll based on a diameter
* @param outerDiameter Outer diameter of the carpet roll
* @param innerDiameter Inner diameter of the carpet roll (the "hole")
* @param numRings Number of "rings" or "layers,"" just like a tree 🙂 🌲
*/
export function diameterToLength(outerDiameter: length_t, innerDiameter: length_t, numRings: number) {
if (outerDiameter.u !== innerDiameter.u) {
throw new Error("diameter units must match!")
}
const thickness = (((outerDiameter.l - innerDiameter.l) / 2) / numRings);
return {
l: Math.PI * (Math.pow(outerDiameter.l, 2) / 4) - (Math.pow(innerDiameter.l, 2) / 4) / thickness,
u: innerDiameter.u,
};
}