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); + }
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 ] @@ -760,6 +760,9 @@ own individual rating by supplying it as the third argument. return arr; };primes(10); // [2,3,5,7] +randomIntArrayInRange
Returns an array of n random integers in the specified range.
Use
Array.from()to create an empty array of the specific length,Math.random()to generate a random number and map it to the desired range, usingMath.floor()to make it an integer.const randomIntArrayInRange = (min, max, n = 1) => + Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min); +randomIntArrayInRange(12, 35, 10); // [ 34, 14, 27, 17, 30, 27, 20, 26, 21, 14 ]randomIntegerInRange
Returns a random integer in the specified range.
Use
Math.random()to generate a random number and map it to the desired range, usingMath.floor()to make it an integer.const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;randomIntegerInRange(0, 5); // 2randomNumberInRange
Returns a random number in the specified range.
Use
Math.random()to generate a random value, map it to the desired range using multiplication.const randomNumberInRange = (min, max) => Math.random() * (max - min) + min; diff --git a/snippets/randomIntArrayInRange.md b/snippets/randomIntArrayInRange.md index e9a341843..a8e38cf2f 100644 --- a/snippets/randomIntArrayInRange.md +++ b/snippets/randomIntArrayInRange.md @@ -6,7 +6,7 @@ Use `Array.from()` to create an empty array of the specific length, `Math.random ```js const randomIntArrayInRange = (min, max, n = 1) => - Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min); + Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min); ``` ```js diff --git a/tag_database b/tag_database index 087c1364f..257a66fb3 100644 --- a/tag_database +++ b/tag_database @@ -140,8 +140,8 @@ pull:array pullAtIndex:array pullAtValue:array randomHexColorCode:utility,random -randomIntegerInRange:math,utility,random randomIntArrayInRange:math,utility,random +randomIntegerInRange:math,utility,random randomNumberInRange:math,utility,random readFileLines:node,array,string redirect:browser,url