From 5afa75ce516577051985ef411303f71a4c17a658 Mon Sep 17 00:00:00 2001 From: Xotic750 Date: Thu, 22 Oct 2015 16:13:02 +0200 Subject: [PATCH] Add `_.toSafeInteger`. --- lodash.js | 28 ++++++++++++++++++++++++++++ test/test.js | 26 +++++++++++++++++++++++++- 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/lodash.js b/lodash.js index 6b6ccd5d6..289b8af5a 100644 --- a/lodash.js +++ b/lodash.js @@ -9771,6 +9771,33 @@ return copyObject(value, keysIn(value)); } + /** + * Converts `value` to a safe integer. A safe integer can be compared and + * represented correctly. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toSafeInteger('3.14'); + * // => 3 + * + * _.toSafeInteger(NaN); + * // => 0 + * + * _.toSafeInteger(Infinity) + * // => 9007199254740991 + * + * _.toSafeInteger(-Infinity) + * // => -9007199254740991 + */ + function toSafeInteger(value) { + return clamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); + } + /** * Converts `value` to a string if it's not one. * An empty string is returned for `null` and `undefined` values. @@ -13102,6 +13129,7 @@ lodash.template = template; lodash.toInteger = toInteger; lodash.toLower = toLower; + lodash.toSafeInteger = toSafeInteger; lodash.toString = toString; lodash.toUpper = toUpper; lodash.trim = trim; diff --git a/test/test.js b/test/test.js index bc6c03f78..3d206a374 100644 --- a/test/test.js +++ b/test/test.js @@ -19170,6 +19170,29 @@ /*--------------------------------------------------------------------------*/ + QUnit.module('lodash.toSafeInteger'); + + (function() { + QUnit.test('should convert values to safe integers', function(assert) { + assert.expect(6); + + assert.strictEqual(_.toSafeInteger(-5.6), -5); + assert.strictEqual(_.toSafeInteger('5.6'), 5); + assert.strictEqual(_.toSafeInteger(), 0); + assert.strictEqual(_.toSafeInteger(NaN), 0); + assert.strictEqual(_.toSafeInteger(Infinity), MAX_SAFE_INTEGER); + assert.strictEqual(_.toSafeInteger(-Infinity), -MAX_SAFE_INTEGER); + }); + + QUnit.test('should support `value` of `-0`', function(assert) { + assert.expect(1); + + assert.strictEqual(1 / _.toSafeInteger(-0), -Infinity); + }); + }()); + + /*--------------------------------------------------------------------------*/ + QUnit.module('lodash.transform'); (function() { @@ -21511,6 +21534,7 @@ 'sum', 'toInteger', 'toLower', + 'toSafeInteger', 'toString', 'toUpper', 'trim', @@ -21762,7 +21786,7 @@ var acceptFalsey = lodashStable.difference(allMethods, rejectFalsey); QUnit.test('should accept falsey arguments', function(assert) { - assert.expect(260); + assert.expect(261); var emptyArrays = lodashStable.map(falsey, lodashStable.constant([]));