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 ]
@@ -952,4 +952,11 @@ console.log(sdbm('age')); // 808122783
yesNo('yes'); // true
yesNo('No'); // false
yesNo('Foo', true); // true
+
Uncategorized
sortedIndex
Returns the lowest index at which value should be inserted into array in order to maintain its sort order.
Check if the array is sorted in descending order (loosely). Use Array.findIndex() to find the appropriate index where the element should be inserted.
const sortedIndex = (arr, n) => {
+ const isDescending = arr[0] > arr[arr.length - 1];
+ const index = arr.findIndex(el => (isDescending ? n >= el : n <= el));
+ return index === -1 ? arr.length : index;
+};
+
sortedIndex([5, 3, 2, 1], 4); // 1
+sortedIndex([30, 50], 40); // 1
\ No newline at end of file
diff --git a/snippets/sortedIndex.md b/snippets/sortedIndex.md
index f83da6ec0..e8d6a6d86 100644
--- a/snippets/sortedIndex.md
+++ b/snippets/sortedIndex.md
@@ -8,12 +8,12 @@ Use `Array.findIndex()` to find the appropriate index where the element should b
```js
const sortedIndex = (arr, n) => {
const isDescending = arr[0] > arr[arr.length - 1];
- const index = arr.findIndex(el => isDescending ? n >= el : n <= el);
+ const index = arr.findIndex(el => (isDescending ? n >= el : n <= el));
return index === -1 ? arr.length : index;
};
```
```js
-sortedIndex([5,3,2,1], 4); // 1
-sortedIndex([30,50],40); // 1
+sortedIndex([5, 3, 2, 1], 4); // 1
+sortedIndex([30, 50], 40); // 1
```
diff --git a/tag_database b/tag_database
index 82a224942..7e280efbd 100644
--- a/tag_database
+++ b/tag_database
@@ -130,6 +130,7 @@ similarity:array
size:object
sleep:function
sortCharactersInString:string
+sortedIndex:uncategorized
speechSynthesis:browser
splitLines:string
spreadOver:adapter