wrapping
v2.1.0
Published
Library for wrapping arithmetic
Downloads
18
Maintainers
Readme
Wrapping
Library for wrapping arithmetic
Install
NPM: npm install --save-dev wrapping
Yarn: yarn add wrapping
TypeScript declaration file is included.
Why
If you want to emulate numeric data types like a uint8
(unsigned 8-bit integer) and perform arithmetic with wrapping semantics.
Example
// Create a new context to operate on unsigned 8-bit numbers
const wrapper = new Wrapping(0, 256 /* 2 ** 8 */);
console.log(wrapper.add(1, 255)); // 0
console.log(wrapper.subtract(0, 1)); // 255
console.log(wrapper.multiply(5, 52)); // 4
API
class Wrapping
constructor(min: number, max: number)
min
and max
must be a finite, safe integer.
Methods:
add(first: number, second: number): number
subtract(first: number, second: number): number
multiply(first: number, second: number): number
divide(first: number, second: number): number
This is redundant, as division between two numbers will never result in overflow. Implemented only for completeness sakes.
wrapNumber(n: number): number
Wraps a number according to the
min
andmax
values set in the constructor. This can be calculated using the formulan - (max - min) - Math.floor((n - min) / (max - min))
.
Motivation
This project was inspired by Rust's Wrapping
struct and the wrapping_add
/wrapping_sub
/wrapping_mul
/wrapping_div
functions.