From be0e7e02d2d5f4e49c792e3e46a88e0c760f071a Mon Sep 17 00:00:00 2001 From: Christopher Jeffrey Date: Sat, 17 Jun 2017 18:19:12 -0700 Subject: [PATCH] util: add isSafeAddition. --- lib/utils/util.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/lib/utils/util.js b/lib/utils/util.js index e98ff10b..aebb15f5 100644 --- a/lib/utils/util.js +++ b/lib/utils/util.js @@ -200,6 +200,14 @@ if (Object.assign) util.MAX_SAFE_INTEGER = 0x1fffffffffffff; +/** + * Max safe addition (52 bits). + * @const {Number} + * @default + */ + +util.MAX_SAFE_ADDITION = 0xfffffffffffff; + /** * Test whether a number is below MAX_SAFE_INTEGER. * @param {Number} value @@ -210,6 +218,19 @@ util.isSafeInteger = function isSafeInteger(value) { return value >= -0x1fffffffffffff && value <= 0x1fffffffffffff; }; +/** + * Test whether the result of a positive + * addition would be below MAX_SAFE_INTEGER. + * @param {Number} value + * @returns {Boolean} + */ + +util.isSafeAddition = function isSafeAddition(a, b) { + assert(a >= 0); + assert(b >= 0); + return a <= util.MAX_SAFE_ADDITION && b <= util.MAX_SAFE_ADDITION; +}; + /** * Test whether a number is Number, * finite, and below MAX_SAFE_INTEGER.