Skip to content

ratio function ​

Divides a value by a total, without NaN or Infinity. Not clamped.

ts
import { ratio } from 'utils';

Signature ​

ts
export function ratio(value: number, total: number): number

Parameters ​

NameDescription
valueThe part.
totalThe whole.

Returns ​

value / total; 0 when total is 0.

Example ​

ts
ratio(5, 10); // 0.5
ratio(5, 0); // 0

Tests ​

Line coverage: 100 %.

  • ✅ computes 5 / 10 as 0.5
  • ✅ computes 15 / 10 as 1.5
  • ✅ computes 5 / 0 as 0
  • ✅ computes 0 / 0 as 0
  • ✅ computes -5 / 10 as -0.5

Source ​

src/math/ratio.ts (on GitHub)

Source code
ts
/**
 * Divides a value by a total, without `NaN` or `Infinity`. Not clamped.
 *
 * @param value - The part.
 * @param total - The whole.
 * @returns `value / total`; `0` when `total` is `0`.
 * @example
 * ratio(5, 10); // 0.5
 * ratio(5, 0); // 0
 */
export function ratio(value: number, total: number): number {
  return total === 0 ? 0 : value / total;
}
Test file
ts
import { ratio } from './ratio';

describe(ratio, () => {
  it.for([
    [5, 10, 0.5],
    [15, 10, 1.5],
    [5, 0, 0],
    [0, 0, 0],
    [-5, 10, -0.5],
  ] as const)('computes %s / %s as %s', ([value, total, expected]) => {
    expect(ratio(value, total)).toBe(expected);
  });
});

Keywords: ratio, math, function

Generated from the JSDoc of the sources.