Compile-to-JavaScript option that uses a Decimal library instead of IEEE 754 math?
在JavaScript
的方法
因此,我正在寻找一种解决方案,该解决方案可以采用类似于以下示例的代码,并带有Decimal的类型注释(使用TypeScript语法)。
1 2 3 4 5 6 | var a:Decimal, b:Decimal, c:Decimal; a = 0.1; b = 0.2; c = a + b; |
编译/宏扩展过程可以输出此代码,该代码使用JavaScript Decimal库(例如,decimal.js),因此c =
1 2 3 4 5 6 | var a, b, c; a = new Decimal(0.1); b = new Decimal(0.2); c = a.plus(b); |
Mozilla sweet.js宏似乎支持自定义运算符,"您可以定义自己的运算符或覆盖内置运算符。"
问题:sweet.js是否可能发生这种情况?有没有类似的例子?
TypeScript转换源代码,并且以前使用TypeScript曾问过这个概念:
- 在TypeScript中实现运算符重载...
- 建议:int类型#195
问题:是否可以扩展TypeScript编译器以支持此用例?这是否适合功能请求?
此外,有关将ActionScript交叉编译到JavaScript的系列中的一篇博客文章得出结论,出于一致性的原因,他们希望" ActionScript和JavaScript中的错误结果相同",但这并未假定附加的类型注释。
问题:是否有其他策略或JavaScript编译选项可以实现此目标?
或者,您可以使用单独的数学库进行所有数学运算。例如math.js附带一个表达式解析器,并支持bignumbers(由decimal.js提供支持):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | math.config({number: 'bignumber'}); // using a parser to manage variables for you in an internal scope: var parser = math.parser(); parser.eval('a = 0.1'); // BigNumber, 0.1 parser.eval('b = 0.2'); // BigNumber, 0.2 parser.eval('c = a + b'); // BigNumber, 0.3 // or without a parser: var scope = {}; math.eval('a = 0.1', scope); // BigNumber, 0.1 math.eval('b = 0.2', scope); // BigNumber, 0.2 math.eval('c = a + b', scope); // BigNumber, 0.3 // scope now contains properties a, b, and c |
我不知道这对于您的应用程序是否可行且方便,但是至少这将使您能够在"可读"表达式中编写方程式。
Is there a compile-to-JavaScript solution that does this today
值得一提的是,它支持运算符覆盖并且具有可选的类型注释,它是Google的Dart:https://www.dartlang.org/
操作员优先:https://www.dartlang.org/articles/idiomatic-dart/#operators
可选类型:https://www.dartlang.org/articles/optional-types/