2.2 KiB
utils
(no submodules)
Purpose
utils.ts provides small, pure mathematical utilities used throughout @suaveplan/colours. Every function is deterministic and side-effect-free, making the module safe to import in any JavaScript runtime. These helpers enforce the numeric invariants that keep colour channels, percentages, and alpha values within their valid ranges.
Features
clamp— restricts a number to a closed intervalisFiniteNumber— type guard rejectingNaNandInfinityroundChannel— clamps and rounds to[0, 255]roundPercent— clamps and rounds to[0, 100]roundAlpha— clamps and rounds to three decimal places in[0, 1]
Usage: Basic Example
import { clamp, roundChannel } from "@suaveplan/colours/utils";
const value = clamp(300, 0, 255);
console.log(value); // 255
const channel = roundChannel(128.6);
console.log(channel); // 129
Usage: Advanced Example
import { isFiniteNumber, roundAlpha } from "@suaveplan/colours/utils";
function safeAlpha(input: unknown): number {
if (!isFiniteNumber(input)) return 1;
return roundAlpha(input);
}
API Reference
clamp(val, min, max): numberisFiniteNumber(v): v is numberroundChannel(v): numberroundPercent(v): numberroundAlpha(v): number
Implementation Notes
roundAlpha uses Math.round(v * 1000) / 1000 to cap precision at three decimal places. This matches the CSS opacity resolution and prevents floating-point drift in serialised output.
All utilities are implemented as standalone functions with no shared state. They can be imported individually for tree-shaking or used together as a consistent numeric toolkit. Because every helper is pure, they are safe to call inside hot loops such as pixel shaders or animation frames without risk of side effects.
The clamp function uses simple comparison operators rather than Math.min and Math.max for slightly better performance in tight loops. The isFiniteNumber guard explicitly rejects NaN and Infinity, which is stricter than a plain typeof check and prevents invalid values from propagating through conversion chains.