Skip to content

Instantly share code, notes, and snippets.

@redblobgames
Created March 21, 2025 15:22
Show Gist options
  • Save redblobgames/a7dd36596be9aef9ae336cd996ba7ada to your computer and use it in GitHub Desktop.
Save redblobgames/a7dd36596be9aef9ae336cd996ba7ada to your computer and use it in GitHub Desktop.
My one line utility functions that I copy into various projects
function clamp(x, lo, hi) { return x < lo ? lo : x > hi ? hi : x; }
function lerp(a, b, t) { return a * (1-t) + b * t; }
function unlerp(a, b, t) { return (t - a) / (b - a); }
function rescale(v, from_lo, from_hi, to_lo, to_hi) { return lerp(to_lo, to_hi, unlerp(from_lo, from_hi, v)); }
function mod(a, b) { return (a % b + b) % b; }
function radiansToDegrees(radians) { return 180 / Math.PI * radians; }
function linearstep(a, b, t) { return clamp(unlerp(a, b, t), 0, 1); }
function smoothstep(a, b, t) { let x = linearstep(a, b, t); return 3 * x**2 - 2 * x**3; }
function randRange(lo, hi) { return Math.floor(Math.random() * (hi-lo)) + lo; }
function randInt(lo, hi) { return randRange(lo, hi+1); }
// writing clamp() this way allows it to work when lo or hi are NaN
// writing linearstep(), smoothstep() this way isntead of clamping t allows it to work when a > b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment