Add toSafeInteger

This commit is contained in:
Angelos Chalaris
2018-01-08 17:12:46 +02:00
parent ef884c666b
commit 5efa8dad90
2 changed files with 17 additions and 0 deletions

16
snippets/toSafeInteger.md Normal file
View File

@ -0,0 +1,16 @@
### toSafeInteger
Converts a value to a safe integer.
Use `Math.max()` and `Math.min()` to find the closest safe value.
Use `Math.round()` to convert to an integer.
```js
const toSafeInteger = num =>
Math.round(Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER));
```
```js
toSafeInteger('3.2'); // 3
toSafeInteger(Infinity); // 9007199254740991
```

View File

@ -165,6 +165,7 @@ toggleClass:browser
toKebabCase:string,regexp toKebabCase:string,regexp
tomorrow:date tomorrow:date
toOrdinalSuffix:utility,math toOrdinalSuffix:utility,math
toSafeInteger:math
toSnakeCase:string,regexp toSnakeCase:string,regexp
truncateString:string truncateString:string
truthCheckCollection:object,logic,array truthCheckCollection:object,logic,array