首页 > 解决方案 > 安全数学课。如何创建可链接的计算?

问题描述

我很难找到要在线搜索的关键字。

我创建了一个具有安全数学函数的类。每个函数接受 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.

标签: javascripttypescriptdeno

解决方案


您可以为此制作一些包装器:

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 )


推荐阅读