Skip to content

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); // 1

Parameters

  • value (number): The value to fold
  • min (number): The minimum value of the range
  • max (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 max are reflected back into the range
  • Values below min are reflected back into the range
  • Reflections repeat for values multiple cycles out of bounds
  • If min equals max, the function returns min
  • If the range is not finite (e.g. max is Infinity), the function returns min
  • 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…
}

MIT Licensed