Functional Weave
Code in Rust

health.bmi@1.0.1

impl/typescript.ts

1,425 bytes · the TypeScript implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

import { roundFloat } from "./math_round_float.ts";  ← from math.round-float ^1.0.0 · built alongside by fune
import { type Bmi, type BmiCategory } from "./health_bmi_types.ts";

function checkRange(name: string, value: number, low: number, high: number, unit: string): void {
  if (typeof value !== "number" || !Number.isFinite(value) || value < low || value > high) {
    throw new RangeError(`${name} must be a number from ${low} to ${high} ${unit}, received ${value}`);
  }
}

/**
 * Body mass index for an adult: weight over height squared, to one decimal
 * place, and the band it falls in. The bands are published to one decimal
 * place (18.5-24.9, 25-29.9, ...), so the category is read from the rounded
 * index: 24.97 is reported as 25.0 and is overweight, not healthy.
 */
export function bmi(weightKg: number, heightCm: number): Bmi {
  checkRange("weightKg", weightKg, 10, 650, "kg");
  // Height in metres (1.75) is the commonest unit slip; 50 cm is the floor.
  checkRange("heightCm", heightCm, 50, 272, "cm");
  const metres = heightCm / 100;
  const value = roundFloat(weightKg / (metres * metres), 1);
  let category: BmiCategory;
  if (value < 18.5) category = "underweight";
  else if (value <= 24.9) category = "healthy-weight";
  else if (value <= 29.9) category = "overweight";
  else if (value <= 34.9) category = "obesity-class-1";
  else if (value <= 39.9) category = "obesity-class-2";
  else category = "obesity-class-3";
  return { value, category };
}