I'm struggling to find the right keywords for my online search regarding this matter.
Recently, I developed a class containing safe math functions. Each function requires 2 arguments and returns the result after undergoing an assertion process.
For instance:
class SafeMath {
static add(x: number, y: number) {
let z: number = x + y;
assert(z >= x, 'ds-math-add-overflow');
return z;
}
static sub(x: number, y: number) {
let z: number = x - y;
assert(z <= x, 'ds-math-sub-underflow');
return z;
}
static mul(x: number, y: number) {
let z: number = x * y;
assert(y == 0 || z / y == x, 'ds-math-mul-overflow');
return z;
}
static div(x: number, y: number) {
let z: number = x / y;
assert(x > 0 || y > 0, 'ds-math-div-by-zero');
return z;
}
}
console.log(SafeMath.add(2,2)); // 4
console.log(SafeMath.sub(2,2)); // 0
console.log(SafeMath.mul(2,2)); // 4
console.log(SafeMath.div(2,2)); // 1
The aim behind these functions is to allow them to operate as follows:
let balance0: number = 1;
let balance1: number = 1;
let amount0In: number = 10;
let amount1In: number = 10;
let balance0Adjusted: number = balance0.mul(1000).sub(amount0In.mul(3));
let balance1Adjusted: number = balance1.mul(1000).sub(amount1In.mul(3));
In this scenario, the functions will take in y
and utilize the preceding number as x
.