@woosh/meep-engine
Version:
Pure JavaScript game engine. Fully featured and production ready.
70 lines (63 loc) • 1.77 kB
JavaScript
/**
* 16-bit modular sequence arithmetic.
*
* Sequence numbers wrap at 65536. When comparing two sequence numbers to decide
* "is A newer than B?", we use the half-range trick: A is newer if the unsigned
* forward distance from B to A is less than 32768. This means a wrapped value
* (like A=10 vs B=65530) is correctly identified as newer.
*
* All functions are pure. They expect both inputs to be valid 16-bit unsigned
* integers; passing larger values produces undefined results.
*
* @author Alex Goldring
* @copyright Company Named Limited (c) 2025
*/
/**
* @type {number}
*/
export const SEQ16_MAX = 0xFFFF;
/**
* @type {number}
*/
export const SEQ16_RANGE = 0x10000;
/**
* @type {number}
*/
export const SEQ16_HALF_RANGE = 0x8000;
/**
* True if `a` is strictly newer than `b` accounting for 16-bit wraparound.
*
* @param {number} a
* @param {number} b
* @returns {boolean}
*/
export function seq16_greater_than(a, b) {
return ((a > b) && (a - b < SEQ16_HALF_RANGE)) ||
((a < b) && (b - a > SEQ16_HALF_RANGE));
}
/**
* Signed forward distance from `from` to `to` accounting for 16-bit wraparound.
* Positive when `to` is newer than `from`, negative when older. Returns 0 for equal sequences.
* Result range: -32768..32767.
*
* @param {number} from
* @param {number} to
* @returns {number}
*/
export function seq16_distance(from, to) {
let d = (to - from) & SEQ16_MAX;
if (d >= SEQ16_HALF_RANGE) {
d -= SEQ16_RANGE;
}
return d;
}
/**
* Advance a sequence by `delta` (which may be negative) with 16-bit wraparound.
*
* @param {number} seq
* @param {number} [delta=1]
* @returns {number}
*/
export function seq16_advance(seq, delta = 1) {
return ((seq + delta) & SEQ16_MAX) >>> 0;
}