javascript - 安全数学课。如何创建可链接的计算?
问题描述
我很难找到要在线搜索的关键字。
我创建了一个具有安全数学函数的类。每个函数接受 2 个参数,在被断言评估后,它返回结果。
例子:
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
我的目标是让这些功能像这样工作,例如:
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));
...函数将接收y
并使用前一个数字作为x
.
解决方案
您可以为此制作一些包装器:
if (!Number.prototype.mul) // check that the mul method does not already exist
{
Number.prototype.mul = function(n){ return this * n }
}
if (!Number.prototype.add)
{
Number.prototype.add = function(n){ return this + n }
}
let val = 5
let doubleValPlus500 = val.mul(2).add(500)
console.log( doubleValPlus500 )
推荐阅读
- .net - ServiceStack 身份验证提供程序OAuthAccess
- java - 使用 OpenJDK 10 的 Gradle JavaFX 项目
- jmeter - 使用 brew 安装时没有 jmeter.properties 文件?
- powershell - powershell 等值校验出错
- cakephp - CakePHP Authorization 插件如何授权访问索引?
- import - SAS Guide 从临时文件夹中读取最新文件
- gradle - Gradle 任务与运行时依赖项混淆
- r - r data.table、sum() 和 by=.() 中的 integer64 类
- elasticsearch - 查询多个应该
- phpunit - PHPUnit\Framework\Error\Warning: ini_set(): 标头已发送。您目前无法更改会话模块的 ini 设置