diff --git a/snippets/toSafeInteger.md b/snippets/toSafeInteger.md new file mode 100644 index 000000000..253778c23 --- /dev/null +++ b/snippets/toSafeInteger.md @@ -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 +``` diff --git a/tag_database b/tag_database index a9862093d..85d09ad53 100644 --- a/tag_database +++ b/tag_database @@ -165,6 +165,7 @@ toggleClass:browser toKebabCase:string,regexp tomorrow:date toOrdinalSuffix:utility,math +toSafeInteger:math toSnakeCase:string,regexp truncateString:string truthCheckCollection:object,logic,array