manufacturing.tolerance-check@1.0.0
impl/typescript.ts
1,671 bytes · the TypeScript implementation · view raw
import { type ToleranceCheck } from "./manufacturing_tolerance_check_types.ts";
const LIMIT = 1_000_000_000_000;
function micrometres(name: string, value: number): number {
if (!Number.isInteger(value) || value > LIMIT || value < -LIMIT) {
throw new RangeError(`${name} must be a whole number of micrometres within ±10^12, received ${value}`);
}
return value;
}
/**
* Check a measurement against nominal plus its upper and lower deviations.
*
* The deviations are signed and independent, so a tolerance band that lies
* wholly above or below nominal (an H7 hole, a g6 shaft) is checked correctly;
* a symmetric band is just `+t, -t`.
*/
export function checkTolerance(measured: number, nominal: number, upperDeviation: number, lowerDeviation: number): ToleranceCheck {
micrometres("measured", measured);
micrometres("nominal", nominal);
micrometres("upperDeviation", upperDeviation);
micrometres("lowerDeviation", lowerDeviation);
if (lowerDeviation > upperDeviation) {
throw new RangeError(
`lowerDeviation must not be greater than upperDeviation, received ${lowerDeviation} and ${upperDeviation}`,
);
}
const lowerLimit = nominal + lowerDeviation;
const upperLimit = nominal + upperDeviation;
const deviation = measured - nominal;
if (measured > upperLimit) {
return { passed: false, status: "above", deviation, lowerLimit, upperLimit, outBy: measured - upperLimit };
}
if (measured < lowerLimit) {
return { passed: false, status: "below", deviation, lowerLimit, upperLimit, outBy: lowerLimit - measured };
}
return { passed: true, status: "within", deviation, lowerLimit, upperLimit, outBy: 0 };
}