diff --git a/README.md b/README.md index 4cf22061e..177725d96 100644 --- a/README.md +++ b/README.md @@ -237,6 +237,7 @@ average(1, 2, 3); * [`standardDeviation`](#standarddeviation) * [`sum`](#sum) * [`sumPower`](#sumpower) +* [`toSafeInteger`](#tosafeinteger) @@ -3468,6 +3469,31 @@ sumPower(10, 3, 5); //2925
[⬆ Back to top](#table-of-contents) + +### 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)); +``` + +
+Examples + +```js +toSafeInteger('3.2'); // 3 +toSafeInteger(Infinity); // 9007199254740991 +``` + +
+ +
[⬆ Back to top](#table-of-contents) + --- ## 📦 Node diff --git a/docs/index.html b/docs/index.html index c4236677e..352b4e736 100644 --- a/docs/index.html +++ b/docs/index.html @@ -40,7 +40,7 @@ },1700); } }, false); - }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Adapter

call

Given a key and a set of arguments, call them when given a context. Primarily useful in composition.

Use a closure to call a stored key with stored arguments.

const call = (key, ...args) => context => context[key](...args);
+      }

logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Adapter

call

Given a key and a set of arguments, call them when given a context. Primarily useful in composition.

Use a closure to call a stored key with stored arguments.

const call = (key, ...args) => context => context[key](...args);
 
Promise.resolve([1, 2, 3])
   .then(call('map', x => 2 * x))
   .then(console.log); //[ 2, 4, 6 ]
@@ -725,6 +725,10 @@ own individual rating by supplying it as the third argument.
 
sumPower(10); // 385
 sumPower(10, 3); //3025
 sumPower(10, 3, 5); //2925
+

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.

const toSafeInteger = num =>
+  Math.round(Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER));
+
toSafeInteger('3.2'); // 3
+toSafeInteger(Infinity); // 9007199254740991
 

Node

hasFlags

Check if the current process's arguments contain the specified flags.

Use Array.every() and Array.includes() to check if process.argv contains all the specified flags. Use a regular expression to test if the specified flags are prefixed with - or -- and prefix them accordingly.

const hasFlags = (...flags) =>
   flags.every(flag => process.argv.includes(/^-{1,2}/.test(flag) ? flag : '--' + flag));
 
// node myScript.js -s --test --cool=true