fold
Fold a value back and forth within a specified range, reflecting it at the bounds ping-pong style.
Usage
js
import { fold } from '@studiometa/js-toolkit/utils';
fold(1, 0, 2); // 1
fold(3, 0, 2); // 1
fold(-1, 0, 2); // 1Parameters
value(number): The value to foldmin(number): The minimum value of the rangemax(number): The maximum value of the range
Return value
number: The folded value within the specified range
Behavior
The fold function ensures that:
- Values above
maxare reflected back into the range - Values below
minare reflected back into the range - Reflections repeat for values multiple cycles out of bounds
- If
minequalsmax, the function returnsmin - If the range is not finite (e.g.
maxisInfinity), the function returnsmin - The result is always within
[min, max](inclusive of both bounds)
Types
ts
function fold(value: number, min: number, max: number): number;Examples
Ping-pong index navigation
js
import { fold } from '@studiometa/js-toolkit/utils';
let currentIndex = 0;
const lastIndex = 4;
// Navigate forward, bouncing at the end
currentIndex = fold(currentIndex + 1, 0, lastIndex); // 1, 2, 3, 4, 3, 2...
// Navigate backward, bouncing at the start
currentIndex = fold(currentIndex - 1, 0, lastIndex); // 1, 0, 1, 2, 3...Sprite sheet scrubbing
js
import { fold } from '@studiometa/js-toolkit/utils';
const frameCount = 8;
// Oscillate through frames: 0 → 7 → 0 → 7…
for (let tick = 0; tick < 20; tick += 1) {
const frame = fold(tick, 0, frameCount - 1); // 0, 1, …, 7, 6, …, 0, 1…
}