Comparing version 0.1.2 to 0.1.3
0.1.3 / 2013-10-23 | ||
================== | ||
* add number utils: toSafeNumber() | ||
0.1.2 / 2013-10-07 | ||
@@ -3,0 +8,0 @@ ================== |
@@ -336,3 +336,39 @@ /*! | ||
// http://www.2ality.com/2013/10/safe-integers.html | ||
exports.MAX_SAFE_INTEGER = Math.pow(2, 53) - 1; | ||
exports.MIN_SAFE_INTEGER = -exports.MAX_SAFE_INTEGER; | ||
var MAX_SAFE_INTEGER_STR = exports.MAX_SAFE_INTEGER_STR = String(exports.MAX_SAFE_INTEGER); | ||
var MAX_SAFE_INTEGER_STR_LENGTH = MAX_SAFE_INTEGER_STR.length; | ||
/** | ||
* Detect a number string can safe convert to Javascript Number. | ||
* | ||
* @param {String} s number format string, like `"123"`, `"-1000123123123123123123"` | ||
* @return {Boolean} | ||
*/ | ||
exports.isSafeNumberString = function (s) { | ||
if (s[0] === '-') { | ||
s = s.substring(1); | ||
} | ||
if (s.length < MAX_SAFE_INTEGER_STR_LENGTH || (s.length === MAX_SAFE_INTEGER_STR_LENGTH && s <= MAX_SAFE_INTEGER_STR)) { | ||
return true; | ||
} | ||
return false; | ||
}; | ||
/** | ||
* Convert string to Number if string in safe Number scope. | ||
* | ||
* @param {String} s number format string. | ||
* @return {Number|String} success will return Number, otherise return the original string. | ||
*/ | ||
exports.toSafeNumber = function (s) { | ||
if (typeof s === 'number') { | ||
return s; | ||
} | ||
return exports.isSafeNumberString(s) ? Number(s) : s; | ||
}; | ||
/** | ||
* Get Unix's timestamp in seconds. | ||
@@ -339,0 +375,0 @@ * @return {Number} |
{ | ||
"name": "utility", | ||
"version": "0.1.2", | ||
"version": "0.1.3", | ||
"description": "A collection of useful utilities.", | ||
@@ -9,3 +9,3 @@ "main": "index.js", | ||
"blanket": { "pattern": "utility/lib" }, | ||
"travis-cov": { "threshold": 98 } | ||
"travis-cov": { "threshold": 99 } | ||
}, | ||
@@ -12,0 +12,0 @@ "dependencies": { |
@@ -77,2 +77,14 @@ utility [![Build Status](https://secure.travis-ci.org/fengmk2/utility.png)](http://travis-ci.org/fengmk2/utility) [![Coverage Status](https://coveralls.io/repos/fengmk2/utility/badge.png)](https://coveralls.io/r/fengmk2/utility) | ||
### Number utils | ||
```js | ||
// Detect a number string can safe convert to Javascript Number.: `-9007199254740991 ~ 9007199254740991` | ||
utils.isSafeNumberString('9007199254740991'); // true | ||
utils.isSafeNumberString('9007199254740993'); // false | ||
// Convert string to number safe: | ||
utils.toSafeNumber('9007199254740991'); // 9007199254740991 | ||
utils.toSafeNumber('9007199254740993'); // '9007199254740993' | ||
``` | ||
## benchmark | ||
@@ -79,0 +91,0 @@ |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
23485
509
169