Wrapping edges


I've been meaning to make a proper note of how to use modulo to keep a number inside a given range by shifting it over to the 'other side' when it passes outside range. It's a basic task, but until recently I've been using if/else statements, which seem a little clumsier than this one-line function.

// wrap edges with if/else
function wrap(x, min, max) {
	if (x < min) {
		x = max;
	} else if (x > max) {
		x = min;
	}

	return x;
}

A example of this from Daniel Shiffman's implementation of Craig Reynold's Boids, which is included in Processing's examples. You can find it under Examples/Topics/Simulate/Flocking.

  void borders() {
    if (position.x < -r) position.x = width+r;
    if (position.y < -r) position.y = height+r;
    if (position.x > width+r) position.x = -r;
    if (position.y > height+r) position.y = -r;
  }

In a simple 2D sketching scenario:
const width = 100;
const height = 100;

let x = Math.random() * 100;
let y = Math.random() * 100;

x = (x + width) % width;
y = (y + height) % height;

Or as a function:

// wrap edges with modulo
function wrap(x, max) {
	return (x + max) % max;
}

One thing to note is that these functions tend to accept a parameter for the maximum value, but assume the minimum value to be 0.

Here is a function that accepts a minimum value parameter:

// wrap edges with modulo
function wrap(x, min, max) {
  const range = max - min;
	return ((x - min + range) % range) + min;
}

which can be simplified further:

// wrap edges with modulo
function wrap(x, min, max) {
	return (((x - min) + (max - min)) % (max - min)) + min;
}