Created
March 21, 2025 15:22
-
-
Save redblobgames/a7dd36596be9aef9ae336cd996ba7ada to your computer and use it in GitHub Desktop.
My one line utility functions that I copy into various projects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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