From 298ee77515b70cf8fd98b906b4d7058e55b1d456 Mon Sep 17 00:00:00 2001 From: atomiks Date: Sat, 30 Dec 2017 23:45:05 +1100 Subject: [PATCH 01/62] Create elo snippet --- snippets/elo.md | 25 +++++++++++++++++++++++++ tag_database | 1 + 2 files changed, 26 insertions(+) create mode 100644 snippets/elo.md diff --git a/snippets/elo.md b/snippets/elo.md new file mode 100644 index 000000000..9d50ba1d0 --- /dev/null +++ b/snippets/elo.md @@ -0,0 +1,25 @@ +### elo + +Computes the new ratings between two opponents using the Elo rating formula. It takes an array +of two pre-ratings and returns an array containing two post-ratings. The winner's rating is be the first element of the array. + +Use `Math.pow()` and math operators to compute the expected score (chance of winning) of each opponent +and compute the change in rating for each. Omit the second argument to use the default K-factor of +32, or supply a custom K-factor value. + +```js +const elo = ([a, b], kFactor = 32) => { + const expectedScore = (self, opponent) => 1 / (1 + Math.pow(10, (opponent - self) / 400)); + const [eA, eB] = [expectedScore(a, b), expectedScore(b, a)]; + const newRating = (rating, index) => + rating + kFactor * ((index === 0 ? 1 : 0) - (index === 0 ? eA : eB)); + return [newRating(a, 0), newRating(b, 1)]; +}; +``` + +```js +elo([1200, 1200]); // [1216, 1184] +elo([1000, 2000]); // [1031.8991261061358, 1968.1008738938642] +elo([1500, 1000]); // [1501.7036868864648, 998.2963131135352] +elo([1200, 1200], 64); // [1232, 1168] +``` diff --git a/tag_database b/tag_database index f5633a5fa..7ca86d900 100644 --- a/tag_database +++ b/tag_database @@ -29,6 +29,7 @@ distinctValuesOfArray:array dropElements:array dropRight:array elementIsVisibleInViewport:browser +elo:math escapeHTML:string escapeRegExp:string everyNth:array From f9344288aafa6c671c9c30a66c3bf8275736ce85 Mon Sep 17 00:00:00 2001 From: atomiks Date: Sat, 30 Dec 2017 23:45:45 +1100 Subject: [PATCH 02/62] Add link --- snippets/elo.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/snippets/elo.md b/snippets/elo.md index 9d50ba1d0..85b54d35b 100644 --- a/snippets/elo.md +++ b/snippets/elo.md @@ -1,7 +1,8 @@ ### elo -Computes the new ratings between two opponents using the Elo rating formula. It takes an array -of two pre-ratings and returns an array containing two post-ratings. The winner's rating is be the first element of the array. +Computes the new ratings between two opponents using the [Elo rating system](https://en.wikipedia.org/wiki/Elo_rating_system). It takes an array +of two pre-ratings and returns an array containing two post-ratings. +The winner's rating is be the first element of the array. Use `Math.pow()` and math operators to compute the expected score (chance of winning) of each opponent and compute the change in rating for each. Omit the second argument to use the default K-factor of From aa617b989fdbefe2c76b90508e2d90d3dbf60e9a Mon Sep 17 00:00:00 2001 From: atomiks Date: Sat, 30 Dec 2017 23:47:43 +1100 Subject: [PATCH 03/62] fix typo --- snippets/elo.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snippets/elo.md b/snippets/elo.md index 85b54d35b..5be73476f 100644 --- a/snippets/elo.md +++ b/snippets/elo.md @@ -2,7 +2,7 @@ Computes the new ratings between two opponents using the [Elo rating system](https://en.wikipedia.org/wiki/Elo_rating_system). It takes an array of two pre-ratings and returns an array containing two post-ratings. -The winner's rating is be the first element of the array. +The winner's rating is the first element of the array. Use `Math.pow()` and math operators to compute the expected score (chance of winning) of each opponent and compute the change in rating for each. Omit the second argument to use the default K-factor of From 71422f5180756d63f67f5e3d143105fe754f6289 Mon Sep 17 00:00:00 2001 From: atomiks Date: Sun, 31 Dec 2017 00:02:46 +1100 Subject: [PATCH 04/62] simplify newRating function --- snippets/elo.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/snippets/elo.md b/snippets/elo.md index 5be73476f..1c52db62b 100644 --- a/snippets/elo.md +++ b/snippets/elo.md @@ -12,9 +12,8 @@ and compute the change in rating for each. Omit the second argument to use the d const elo = ([a, b], kFactor = 32) => { const expectedScore = (self, opponent) => 1 / (1 + Math.pow(10, (opponent - self) / 400)); const [eA, eB] = [expectedScore(a, b), expectedScore(b, a)]; - const newRating = (rating, index) => - rating + kFactor * ((index === 0 ? 1 : 0) - (index === 0 ? eA : eB)); - return [newRating(a, 0), newRating(b, 1)]; + const newRating = (rating, index) => rating + kFactor * (index - (index ? eA : eB)); + return [newRating(a, 1), newRating(b, 0)]; }; ``` From 3ef1d1dc36b767788dafb0a32ae0473db415c46f Mon Sep 17 00:00:00 2001 From: atomiks Date: Sun, 31 Dec 2017 17:13:05 +1100 Subject: [PATCH 05/62] Optimise further --- snippets/elo.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/snippets/elo.md b/snippets/elo.md index 1c52db62b..991b74019 100644 --- a/snippets/elo.md +++ b/snippets/elo.md @@ -5,14 +5,14 @@ of two pre-ratings and returns an array containing two post-ratings. The winner's rating is the first element of the array. Use `Math.pow()` and math operators to compute the expected score (chance of winning) of each opponent -and compute the change in rating for each. Omit the second argument to use the default K-factor of +and compute the new rating for each. Omit the second argument to use the default K-factor of 32, or supply a custom K-factor value. ```js const elo = ([a, b], kFactor = 32) => { const expectedScore = (self, opponent) => 1 / (1 + Math.pow(10, (opponent - self) / 400)); - const [eA, eB] = [expectedScore(a, b), expectedScore(b, a)]; - const newRating = (rating, index) => rating + kFactor * (index - (index ? eA : eB)); + const newRating = (rating, i) => + rating + kFactor * (i - (i ? expectedScore(a, b) : expectedScore(b, a))); return [newRating(a, 1), newRating(b, 0)]; }; ``` From cb0d65826eb20985892745fd9c4114a179e992c2 Mon Sep 17 00:00:00 2001 From: atomiks Date: Sun, 31 Dec 2017 17:19:55 +1100 Subject: [PATCH 06/62] Avoid repeating function call --- snippets/elo.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/snippets/elo.md b/snippets/elo.md index 991b74019..1fbbe1986 100644 --- a/snippets/elo.md +++ b/snippets/elo.md @@ -11,8 +11,7 @@ and compute the new rating for each. Omit the second argument to use the default ```js const elo = ([a, b], kFactor = 32) => { const expectedScore = (self, opponent) => 1 / (1 + Math.pow(10, (opponent - self) / 400)); - const newRating = (rating, i) => - rating + kFactor * (i - (i ? expectedScore(a, b) : expectedScore(b, a))); + const newRating = (rating, i) => rating + kFactor * (i - expectedScore(i ? a : b, i ? b : a)); return [newRating(a, 1), newRating(b, 0)]; }; ``` From dc1322f72b56ea0b7bc4b768504404e7376efcc3 Mon Sep 17 00:00:00 2001 From: atomiks Date: Sun, 31 Dec 2017 19:04:35 +1100 Subject: [PATCH 07/62] switch to exponent operator --- snippets/elo.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/snippets/elo.md b/snippets/elo.md index 1fbbe1986..671d1ccea 100644 --- a/snippets/elo.md +++ b/snippets/elo.md @@ -4,13 +4,13 @@ Computes the new ratings between two opponents using the [Elo rating system](htt of two pre-ratings and returns an array containing two post-ratings. The winner's rating is the first element of the array. -Use `Math.pow()` and math operators to compute the expected score (chance of winning) of each opponent -and compute the new rating for each. Omit the second argument to use the default K-factor of -32, or supply a custom K-factor value. +Use the exponent `**` operator and math operators to compute the expected score (chance of winning) +of each opponent and compute the new rating for each. Omit the second argument to use the default +K-factor of 32, or supply a custom K-factor value. ```js const elo = ([a, b], kFactor = 32) => { - const expectedScore = (self, opponent) => 1 / (1 + Math.pow(10, (opponent - self) / 400)); + const expectedScore = (self, opponent) => 1 / (1 + 10 ** ((opponent - self) / 400)); const newRating = (rating, i) => rating + kFactor * (i - expectedScore(i ? a : b, i ? b : a)); return [newRating(a, 1), newRating(b, 0)]; }; From 138fd3ec9b75c897b54ccac69f06abff83bfcf07 Mon Sep 17 00:00:00 2001 From: atomiks Date: Sun, 31 Dec 2017 21:48:13 +1100 Subject: [PATCH 08/62] Add isPrimitive utility snippet --- snippets/isPrimitive.md | 22 ++++++++++++++++++++++ tag_database | 1 + 2 files changed, 23 insertions(+) create mode 100644 snippets/isPrimitive.md diff --git a/snippets/isPrimitive.md b/snippets/isPrimitive.md new file mode 100644 index 000000000..cd90501b3 --- /dev/null +++ b/snippets/isPrimitive.md @@ -0,0 +1,22 @@ +### isPrimitive + +Returns a boolean determining if the supplied value is primitive or not. + +Use `Array.includes()` on an array of type strings, supplying the type using `typeof`. +Since `typeof null` evaluates to `'object'`, it needs to be directly compared. + +```js +const isPrimitive = value => + ['string', 'number', 'symbol', 'boolean', 'undefined'].includes(typeof value) || value === null; +``` + +```js +isPrimitive(window.someNonExistentProperty); // true +isPrimitive(null); // true +isPrimitive(50); // true +isPrimitive('Hello!'); // true +isPrimitive(false); // true +isPrimitive(Symbol()); // true +isPrimitive([]); // false +isPrimitive(new String('Hello!')); // false +``` diff --git a/tag_database b/tag_database index d897e319c..9287acd90 100644 --- a/tag_database +++ b/tag_database @@ -71,6 +71,7 @@ isEven:math isFunction:utility isNumber:utility isPrime:math +isPrimitive:utility isString:utility isSymbol:utility JSONToDate:date From 7bb5865b70108024e0c4bef7197d2cfbab0f4061 Mon Sep 17 00:00:00 2001 From: atomiks Date: Sun, 31 Dec 2017 22:55:55 +1100 Subject: [PATCH 09/62] Add memoize snippet --- snippets/memoize.md | 23 +++++++++++++++++++++++ tag_database | 1 + 2 files changed, 24 insertions(+) create mode 100644 snippets/memoize.md diff --git a/snippets/memoize.md b/snippets/memoize.md new file mode 100644 index 000000000..8a71702e1 --- /dev/null +++ b/snippets/memoize.md @@ -0,0 +1,23 @@ +### memoize + +Returns the memoized (cached) function. + +Use `Object.create(null)` to create an empty object without Object.prototype +(so that those properties are not resolved if the input value is something like 'hasOwnProperty'). +Return a function which takes a single argument to be supplied to the memoized function +by first checking if the function's output for that specific input value is already cached, or +store and return it if not. + +```js +const memoize = fn => { + const cache = Object.create(null); + return value => cache[value] || (cache[value] = fn(value)); +}; +``` + +```js +// See the `anagrams` snippet. +const anagramsCached = memoize(anagrams); +anagramsCached('javascript'); // takes a long time +anagramsCached('javascript'); // returns virtually instantly since it's now cached +``` diff --git a/tag_database b/tag_database index d897e319c..f82dd92c5 100644 --- a/tag_database +++ b/tag_database @@ -81,6 +81,7 @@ lowercaseKeys:object mapObject:array max:math median:math +memoize:function min:math negate:logic nthElement:array From 94315f0315c465cf977cdf298161d28dde88559f Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sun, 31 Dec 2017 13:57:41 +0200 Subject: [PATCH 10/62] Added list of collaborators to the README --- static-parts/README-end.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/static-parts/README-end.md b/static-parts/README-end.md index c9d2d14b1..8b9c13e84 100644 --- a/static-parts/README-end.md +++ b/static-parts/README-end.md @@ -1,3 +1,10 @@ +## Collaborators + +| [](https://github.com/Chalarangelo)
[Angelos Chalaris](https://github.com/Chalarangelo) | [](https://github.com/Pl4gue)
[David Wu](https://github.com/Pl4gue) | [](https://github.com/fejes713)
[Stefan Feješ](https://github.com/fejes713) | [](https://github.com/kingdavidmartins)
[King David Martins](https://github.com/iamsoorena) | [](https://github.com/iamsoorena)
[Soorena Soleimani](https://github.com/iamsoorena) | +| --- | --- | --- | --- | --- | +| [](https://github.com/elderhsouza)
[Elder Henrique Souza](https://github.com/elderhsouza) | [](https://github.com/skatcat31)
[Robert Mennell](https://github.com/skatcat31) | [](https://github.com/atomiks)
[atomiks](https://github.com/atomiks) | + + ## Credits *Icons made by [Smashicons](https://www.flaticon.com/authors/smashicons) from [www.flaticon.com](https://www.flaticon.com/) is licensed by [CC 3.0 BY](http://creativecommons.org/licenses/by/3.0/).* From 3b0ce8a1ab903b8d9e0d15c4b3a76b4420783396 Mon Sep 17 00:00:00 2001 From: Travis CI Date: Sun, 31 Dec 2017 11:58:36 +0000 Subject: [PATCH 11/62] Travis build: 702 [ci skip] --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index 9cdeb42e2..6a6b16b23 100644 --- a/README.md +++ b/README.md @@ -4332,6 +4332,13 @@ yesNo('Foo', true); // true
[⬆ Back to top](#table-of-contents) +## Collaborators + +| [](https://github.com/Chalarangelo)
[Angelos Chalaris](https://github.com/Chalarangelo) | [](https://github.com/Pl4gue)
[David Wu](https://github.com/Pl4gue) | [](https://github.com/fejes713)
[Stefan Feješ](https://github.com/fejes713) | [](https://github.com/kingdavidmartins)
[King David Martins](https://github.com/iamsoorena) | [](https://github.com/iamsoorena)
[Soorena Soleimani](https://github.com/iamsoorena) | +| --- | --- | --- | --- | --- | +| [](https://github.com/elderhsouza)
[Elder Henrique Souza](https://github.com/elderhsouza) | [](https://github.com/skatcat31)
[Robert Mennell](https://github.com/skatcat31) | [](https://github.com/atomiks)
[atomiks](https://github.com/atomiks) | + + ## Credits *Icons made by [Smashicons](https://www.flaticon.com/authors/smashicons) from [www.flaticon.com](https://www.flaticon.com/) is licensed by [CC 3.0 BY](http://creativecommons.org/licenses/by/3.0/).* From ba2706cd7ed499e3830591e71dc3c9075439b6d3 Mon Sep 17 00:00:00 2001 From: Travis CI Date: Sun, 31 Dec 2017 12:01:13 +0000 Subject: [PATCH 12/62] Travis build: 703 [ci skip] --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6a6b16b23..01f416b3c 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,7 @@ -### 🖥️ Browser +### 🌐 Browser
View contents @@ -1437,7 +1437,7 @@ zipObject(['a', 'b'], [1, 2, 3]); // {a: 1, b: 2}
[⬆ Back to top](#table-of-contents) --- - ## 🖥️ Browser + ## 🌐 Browser ### arrayToHtmlList From 555743e0c517d0ad8fe63b085bf18557e96ab38f Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sun, 31 Dec 2017 14:04:44 +0200 Subject: [PATCH 13/62] Update memoize.md --- snippets/memoize.md | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/snippets/memoize.md b/snippets/memoize.md index 8a71702e1..c1b6b1343 100644 --- a/snippets/memoize.md +++ b/snippets/memoize.md @@ -2,11 +2,8 @@ Returns the memoized (cached) function. -Use `Object.create(null)` to create an empty object without Object.prototype -(so that those properties are not resolved if the input value is something like 'hasOwnProperty'). -Return a function which takes a single argument to be supplied to the memoized function -by first checking if the function's output for that specific input value is already cached, or -store and return it if not. +Use `Object.create(null)` to create an empty object without `Object.prototype` (so that those properties are not resolved if the input value is something like `'hasOwnProperty'`). +Return a function which takes a single argument to be supplied to the memoized function by first checking if the function's output for that specific input value is already cached, or store and return it if not. ```js const memoize = fn => { From c9a1d9301d1eb540a1607e8f707e967f33e47c39 Mon Sep 17 00:00:00 2001 From: Travis CI Date: Sun, 31 Dec 2017 12:07:56 +0000 Subject: [PATCH 14/62] Travis build: 707 [ci skip] --- README.md | 30 ++++++++++++++++++++++++++++++ docs/index.html | 10 +++++++++- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 01f416b3c..2bcb93460 100644 --- a/README.md +++ b/README.md @@ -126,6 +126,7 @@ * [`compose`](#compose) * [`curry`](#curry) * [`functionName`](#functionname) +* [`memoize`](#memoize) * [`runPromisesInSeries`](#runpromisesinseries) * [`sleep`](#sleep) @@ -2176,6 +2177,35 @@ functionName(Math.max); // max (logged in debug channel of console)
[⬆ Back to top](#table-of-contents) +### memoize + +Returns the memoized (cached) function. + +Use `Object.create(null)` to create an empty object without `Object.prototype` (so that those properties are not resolved if the input value is something like `'hasOwnProperty'`). +Return a function which takes a single argument to be supplied to the memoized function by first checking if the function's output for that specific input value is already cached, or store and return it if not. + +```js +const memoize = fn => { + const cache = Object.create(null); + return value => cache[value] || (cache[value] = fn(value)); +}; +``` + +
+Examples + +```js +// See the `anagrams` snippet. +const anagramsCached = memoize(anagrams); +anagramsCached('javascript'); // takes a long time +anagramsCached('javascript'); // returns virtually instantly since it's now cached +``` + +
+ +
[⬆ Back to top](#table-of-contents) + + ### runPromisesInSeries Runs an array of promises in series. diff --git a/docs/index.html b/docs/index.html index 2acf4f2bb..d10bb750a 100644 --- a/docs/index.html +++ b/docs/index.html @@ -59,7 +59,7 @@ wrapper.appendChild(box); box.appendChild(el); }); - }

 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);
+    }

 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 ]
@@ -436,6 +436,14 @@ multiplyAndAdd5(5, 2); // 15
 curry(Math.min, 3)(10)(50)(2); // 2
 

functionName

Logs the name of a function.

Use console.debug() and the name property of the passed method to log the method's name to the debug channel of the console.

const functionName = fn => (console.debug(fn.name), fn);
 
functionName(Math.max); // max (logged in debug channel of console)
+

memoize

Returns the memoized (cached) function.

Use Object.create(null) to create an empty object without Object.prototype (so that those properties are not resolved if the input value is something like 'hasOwnProperty'). Return a function which takes a single argument to be supplied to the memoized function by first checking if the function's output for that specific input value is already cached, or store and return it if not.

const memoize = fn => {
+  const cache = Object.create(null);
+  return value => cache[value] || (cache[value] = fn(value));
+};
+
// See the `anagrams` snippet.
+const anagramsCached = memoize(anagrams);
+anagramsCached('javascript'); // takes a long time
+anagramsCached('javascript'); // returns virtually instantly since it's now cached
 

runPromisesInSeries

Runs an array of promises in series.

Use Array.reduce() to create a promise chain, where each promise returns the next promise when resolved.

const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve());
 
const delay = d => new Promise(r => setTimeout(r, d));
 runPromisesInSeries([() => delay(1000), () => delay(2000)]); // //executes each promise sequentially, taking a total of 3 seconds to complete

From 1fd8ea262e907ca6dc3d68854fe7479bcd6c0e3d Mon Sep 17 00:00:00 2001
From: Travis CI 
Date: Sun, 31 Dec 2017 12:13:21 +0000
Subject: [PATCH 15/62] Travis build: 710 [ci skip]

---
 README.md              | 38 ++++++++++++++++++++++++++++++++++++++
 docs/index.html        | 12 +++++++++++-
 snippets/sampleSize.md | 10 +++++-----
 tag_database           |  1 +
 4 files changed, 55 insertions(+), 6 deletions(-)

diff --git a/README.md b/README.md
index 2bcb93460..f185c714d 100644
--- a/README.md
+++ b/README.md
@@ -260,6 +260,15 @@
 
 
+### _Uncategorized_ + +
+View contents + +* [`sampleSize`](#samplesize) + +
+ --- ## 🔌 Adapter @@ -4361,6 +4370,35 @@ yesNo('Foo', true); // true
[⬆ Back to top](#table-of-contents) +--- + ## _Uncategorized_ + +### sampleSize + +Gets `n` random elements at unique keys from `array` up to the size of `array`. + +Shuffle the array using the [Fisher-Yates algorithm](https://github.com/chalarangelo/30-seconds-of-code#shuffle). +Use `Array.slice()` to get the first `n` elements. +Omit the second argument, `n` to get only one element at random from the array. + +```js +const sampleSize = ([...arr], n = 1) => { + let m = arr.length; + while (m) { + const i = Math.floor(Math.random() * m--); + [arr[m], arr[i]] = [arr[i], arr[m]]; + } + return arr.slice(0, n); +}; +``` + +```js +sampleSize([1, 2, 3], 2); // [3,1] +sampleSize([1, 2, 3], 4); // [2,3,1] +``` + +
[⬆ back to top](#table-of-contents) + ## Collaborators diff --git a/docs/index.html b/docs/index.html index d10bb750a..6a66cb59d 100644 --- a/docs/index.html +++ b/docs/index.html @@ -59,7 +59,7 @@ wrapper.appendChild(box); box.appendChild(el); }); - }

 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);
+    }

 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 ]
@@ -905,4 +905,14 @@ console.log(sdbm('age')); // 808122783
 yesNo('yes'); // true
 yesNo('No'); // false
 yesNo('Foo', true); // true
+

Uncategorized

sampleSize

Gets n random elements at unique keys from array up to the size of array.

Shuffle the array using the Fisher-Yates algorithm. Use Array.slice() to get the first n elements. Omit the second argument, n to get only one element at random from the array.

const sampleSize = ([...arr], n = 1) => {
+  let m = arr.length;
+  while (m) {
+    const i = Math.floor(Math.random() * m--);
+    [arr[m], arr[i]] = [arr[i], arr[m]];
+  }
+  return arr.slice(0, n);
+};
+
sampleSize([1, 2, 3], 2); // [3,1]
+sampleSize([1, 2, 3], 4); // [2,3,1]
 

\ No newline at end of file diff --git a/snippets/sampleSize.md b/snippets/sampleSize.md index f6187bdea..7b2480cba 100644 --- a/snippets/sampleSize.md +++ b/snippets/sampleSize.md @@ -7,17 +7,17 @@ Use `Array.slice()` to get the first `n` elements. Omit the second argument, `n` to get only one element at random from the array. ```js -const sampleSize = ([...arr],n=1) => { +const sampleSize = ([...arr], n = 1) => { let m = arr.length; while (m) { const i = Math.floor(Math.random() * m--); [arr[m], arr[i]] = [arr[i], arr[m]]; } - return arr.slice(0,n) -} + return arr.slice(0, n); +}; ``` ```js -sampleSize([1,2,3],2); // [3,1] -sampleSize([1,2,3],4); // [2,3,1] +sampleSize([1, 2, 3], 2); // [3,1] +sampleSize([1, 2, 3], 4); // [2,3,1] ``` diff --git a/tag_database b/tag_database index db90b4d02..b06cb8280 100644 --- a/tag_database +++ b/tag_database @@ -114,6 +114,7 @@ RGBToHex:utility round:math runPromisesInSeries:function sample:array +sampleSize:uncategorized scrollToTop:browser sdbm:utility select:object From 6ad3e69739d5e31e1efa87204bbe7e835ab4de18 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sun, 31 Dec 2017 14:14:23 +0200 Subject: [PATCH 16/62] Update tag_database --- tag_database | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tag_database b/tag_database index b06cb8280..e2bb75c7e 100644 --- a/tag_database +++ b/tag_database @@ -114,7 +114,7 @@ RGBToHex:utility round:math runPromisesInSeries:function sample:array -sampleSize:uncategorized +sampleSize:array scrollToTop:browser sdbm:utility select:object From 04a804bfb5cacdb1e6fd195204371b0f6d527c33 Mon Sep 17 00:00:00 2001 From: Travis CI Date: Sun, 31 Dec 2017 12:15:19 +0000 Subject: [PATCH 17/62] Travis build: 711 [ci skip] --- README.md | 71 +++++++++++++++++++++++-------------------------- docs/index.html | 22 +++++++-------- 2 files changed, 44 insertions(+), 49 deletions(-) diff --git a/README.md b/README.md index f185c714d..6659888fa 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,7 @@ * [`quickSort`](#quicksort) * [`remove`](#remove) * [`sample`](#sample) +* [`sampleSize`](#samplesize) * [`shuffle`](#shuffle) * [`similarity`](#similarity) * [`symmetricDifference`](#symmetricdifference) @@ -260,15 +261,6 @@ -### _Uncategorized_ - -
-View contents - -* [`sampleSize`](#samplesize) - -
- --- ## 🔌 Adapter @@ -1199,6 +1191,38 @@ sample([3, 7, 9, 11]); // 9
[⬆ Back to top](#table-of-contents) +### sampleSize + +Gets `n` random elements at unique keys from `array` up to the size of `array`. + +Shuffle the array using the [Fisher-Yates algorithm](https://github.com/chalarangelo/30-seconds-of-code#shuffle). +Use `Array.slice()` to get the first `n` elements. +Omit the second argument, `n` to get only one element at random from the array. + +```js +const sampleSize = ([...arr], n = 1) => { + let m = arr.length; + while (m) { + const i = Math.floor(Math.random() * m--); + [arr[m], arr[i]] = [arr[i], arr[m]]; + } + return arr.slice(0, n); +}; +``` + +
+Examples + +```js +sampleSize([1, 2, 3], 2); // [3,1] +sampleSize([1, 2, 3], 4); // [2,3,1] +``` + +
+ +
[⬆ Back to top](#table-of-contents) + + ### shuffle Randomizes the order of the values of an array, returning a new array. @@ -4370,35 +4394,6 @@ yesNo('Foo', true); // true
[⬆ Back to top](#table-of-contents) ---- - ## _Uncategorized_ - -### sampleSize - -Gets `n` random elements at unique keys from `array` up to the size of `array`. - -Shuffle the array using the [Fisher-Yates algorithm](https://github.com/chalarangelo/30-seconds-of-code#shuffle). -Use `Array.slice()` to get the first `n` elements. -Omit the second argument, `n` to get only one element at random from the array. - -```js -const sampleSize = ([...arr], n = 1) => { - let m = arr.length; - while (m) { - const i = Math.floor(Math.random() * m--); - [arr[m], arr[i]] = [arr[i], arr[m]]; - } - return arr.slice(0, n); -}; -``` - -```js -sampleSize([1, 2, 3], 2); // [3,1] -sampleSize([1, 2, 3], 4); // [2,3,1] -``` - -
[⬆ back to top](#table-of-contents) - ## Collaborators diff --git a/docs/index.html b/docs/index.html index 6a66cb59d..f36e25510 100644 --- a/docs/index.html +++ b/docs/index.html @@ -59,7 +59,7 @@ wrapper.appendChild(box); box.appendChild(el); }); - }

 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);
+    }

 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 ]
@@ -236,6 +236,16 @@ quickSort([4, 1, 3, 2], true); // [4,3,2,1]
 
remove([1, 2, 3, 4], n => n % 2 == 0); // [2, 4]
 

sample

Returns a random element from an array.

Use Math.random() to generate a random number, multiply it by length and round it of to the nearest whole number using Math.floor(). This method also works with strings.

const sample = arr => arr[Math.floor(Math.random() * arr.length)];
 
sample([3, 7, 9, 11]); // 9
+

sampleSize

Gets n random elements at unique keys from array up to the size of array.

Shuffle the array using the Fisher-Yates algorithm. Use Array.slice() to get the first n elements. Omit the second argument, n to get only one element at random from the array.

const sampleSize = ([...arr], n = 1) => {
+  let m = arr.length;
+  while (m) {
+    const i = Math.floor(Math.random() * m--);
+    [arr[m], arr[i]] = [arr[i], arr[m]];
+  }
+  return arr.slice(0, n);
+};
+
sampleSize([1, 2, 3], 2); // [3,1]
+sampleSize([1, 2, 3], 4); // [2,3,1]
 

shuffle

Randomizes the order of the values of an array, returning a new array.

Uses the Fisher-Yates algoritm to reorder the elements of the array, based on the Lodash implementation, but as a pure function.

const shuffle = ([...arr]) => {
   let m = arr.length;
   while (m) {
@@ -905,14 +915,4 @@ console.log(sdbm('age')); // 808122783
 yesNo('yes'); // true
 yesNo('No'); // false
 yesNo('Foo', true); // true
-

Uncategorized

sampleSize

Gets n random elements at unique keys from array up to the size of array.

Shuffle the array using the Fisher-Yates algorithm. Use Array.slice() to get the first n elements. Omit the second argument, n to get only one element at random from the array.

const sampleSize = ([...arr], n = 1) => {
-  let m = arr.length;
-  while (m) {
-    const i = Math.floor(Math.random() * m--);
-    [arr[m], arr[i]] = [arr[i], arr[m]];
-  }
-  return arr.slice(0, n);
-};
-
sampleSize([1, 2, 3], 2); // [3,1]
-sampleSize([1, 2, 3], 4); // [2,3,1]
 

\ No newline at end of file From a2359a7c229db3bc111f47a86c889216951162ef Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sun, 31 Dec 2017 14:20:21 +0200 Subject: [PATCH 18/62] Add isPromise snippet --- snippets/isPromise.md | 16 ++++++++++++++++ tag_database | 1 + 2 files changed, 17 insertions(+) create mode 100644 snippets/isPromise.md diff --git a/snippets/isPromise.md b/snippets/isPromise.md new file mode 100644 index 000000000..7a6e32d3f --- /dev/null +++ b/snippets/isPromise.md @@ -0,0 +1,16 @@ +### isPromise + +Returns `true` if an object looks like a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise), `false` otherwise. + +Check if the object is not `null`, its `typeof` matches either `object` or `function` and if it has a `.then` property, which is also a `function`. + +```js +const isPromise = obj => + obj !== null && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'; +``` + +```js +isPromise({then:function () {return ''}}); // true +isPromise(null); // false +isPromise({}); // false +``` diff --git a/tag_database b/tag_database index e2bb75c7e..5c9edee5d 100644 --- a/tag_database +++ b/tag_database @@ -73,6 +73,7 @@ isFunction:utility isNull:utility isNumber:utility isPrime:math +isPromise:utility isString:utility isSymbol:utility JSONToDate:date From be3f67971f936ae0a6f028e76a59890762fc8df3 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sun, 31 Dec 2017 14:25:43 +0200 Subject: [PATCH 19/62] Update and rename isPromise.md to isPromiseLike.md --- snippets/{isPromise.md => isPromiseLike.md} | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) rename snippets/{isPromise.md => isPromiseLike.md} (73%) diff --git a/snippets/isPromise.md b/snippets/isPromiseLike.md similarity index 73% rename from snippets/isPromise.md rename to snippets/isPromiseLike.md index 7a6e32d3f..d7bb9a75b 100644 --- a/snippets/isPromise.md +++ b/snippets/isPromiseLike.md @@ -1,16 +1,16 @@ -### isPromise +### isPromiseLike Returns `true` if an object looks like a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise), `false` otherwise. Check if the object is not `null`, its `typeof` matches either `object` or `function` and if it has a `.then` property, which is also a `function`. ```js -const isPromise = obj => +const isPromiseLike = obj => obj !== null && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'; ``` ```js -isPromise({then:function () {return ''}}); // true -isPromise(null); // false -isPromise({}); // false +isPromiseLike({then:function () {return ''}}); // true +isPromiseLike(null); // false +isPromiseLike({}); // false ``` From b4ecf35ad236a5075cfff1ee89d791cf904d511d Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sun, 31 Dec 2017 14:25:55 +0200 Subject: [PATCH 20/62] Update tag_database --- tag_database | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tag_database b/tag_database index 5c9edee5d..750f9d0bd 100644 --- a/tag_database +++ b/tag_database @@ -73,7 +73,7 @@ isFunction:utility isNull:utility isNumber:utility isPrime:math -isPromise:utility +isPromiseLike:utility isString:utility isSymbol:utility JSONToDate:date From 02a5c628e96375589e3d894aff84f38bebe66929 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sun, 31 Dec 2017 14:42:45 +0200 Subject: [PATCH 21/62] Add isAbsoluteURL --- snippets/isAbsoluteURL.md | 15 +++++++++++++++ tag_database | 1 + 2 files changed, 16 insertions(+) create mode 100644 snippets/isAbsoluteURL.md diff --git a/snippets/isAbsoluteURL.md b/snippets/isAbsoluteURL.md new file mode 100644 index 000000000..8f13f5861 --- /dev/null +++ b/snippets/isAbsoluteURL.md @@ -0,0 +1,15 @@ +### isAbsoluteURL + +Returns `true` if the given string is an absolute URL, `false` otherwise. + +Use a regular expression to test if the string is an absolute URL. + +```js +const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str); +``` + +```js +isAbsoluteURL('https://google.com'); // true +isAbsoluteURL('ftp://www.myserver.net'); // true +isAbsoluteURL('/foo/bar'); // false +``` diff --git a/tag_database b/tag_database index e2bb75c7e..716ff171b 100644 --- a/tag_database +++ b/tag_database @@ -64,6 +64,7 @@ initializeArrayWithRange:array initializeArrayWithValues:array inRange:math intersection:array +isAbsoluteURL:string isArmstrongNumber:math isArray:utility isBoolean:utility From 42509bbb9b6dfcd0724faeca4714c45fe69ac391 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sun, 31 Dec 2017 14:44:49 +0200 Subject: [PATCH 22/62] Removes the ironic capitalization from capitalize's title --- snippets/capitalize.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snippets/capitalize.md b/snippets/capitalize.md index 802bd7a4f..f9a26e7be 100644 --- a/snippets/capitalize.md +++ b/snippets/capitalize.md @@ -1,4 +1,4 @@ -### Capitalize +### capitalize Capitalizes the first letter of a string. From ead9b790081065b163f3129d31e3319a1155722e Mon Sep 17 00:00:00 2001 From: Travis CI Date: Sun, 31 Dec 2017 12:45:44 +0000 Subject: [PATCH 23/62] Travis build: 720 [ci skip] --- README.md | 2 +- docs/index.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6659888fa..036edc432 100644 --- a/README.md +++ b/README.md @@ -3418,7 +3418,7 @@ byteSize('Hello World'); // 11
[⬆ Back to top](#table-of-contents) -### Capitalize +### capitalize Capitalizes the first letter of a string. diff --git a/docs/index.html b/docs/index.html index f36e25510..5c06dd1eb 100644 --- a/docs/index.html +++ b/docs/index.html @@ -690,7 +690,7 @@ size({ one: 1, two: 2, three: 3 }); // 3

byteSize

Returns the length of string.

Convert a given string to a Blob Object and find its size.

const byteSize = str => new Blob([str]).size;
 
byteSize('😀'); // 4
 byteSize('Hello World'); // 11
-

Capitalize

Capitalizes the first letter of a string.

Use destructuring and toUpperCase() to capitalize first letter, ...rest to get array of characters after first letter and then Array.join('') to make it a string again. Omit the lowerRest parameter to keep the rest of the string intact, or set it to true to convert to lowercase.

const capitalize = ([first, ...rest], lowerRest = false) =>
+

capitalize

Capitalizes the first letter of a string.

Use destructuring and toUpperCase() to capitalize first letter, ...rest to get array of characters after first letter and then Array.join('') to make it a string again. Omit the lowerRest parameter to keep the rest of the string intact, or set it to true to convert to lowercase.

const capitalize = ([first, ...rest], lowerRest = false) =>
   first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join(''));
 
capitalize('fooBar'); // 'FooBar'
 capitalize('fooBar', true); // 'Foobar'

From 5a4905925ab9eefc795973260ad87fc4cb0f7246 Mon Sep 17 00:00:00 2001
From: Travis CI 
Date: Sun, 31 Dec 2017 13:06:22 +0000
Subject: [PATCH 24/62] Travis build: 727 [ci skip]

---
 README.md               | 63 +++++++++++++++++++++++++++++++++++++++++
 docs/index.html         | 23 ++++++++++++++-
 snippets/isArrayLike.md | 13 ++++-----
 snippets/isValidJSON.md |  7 ++---
 tag_database            |  2 ++
 5 files changed, 96 insertions(+), 12 deletions(-)

diff --git a/README.md b/README.md
index 036edc432..f2b0a62bc 100644
--- a/README.md
+++ b/README.md
@@ -261,6 +261,16 @@
 
 
 
+### _Uncategorized_
+
+
+View contents + +* [`isArrayLike`](#isarraylike) +* [`isValidJSON`](#isvalidjson) + +
+ --- ## 🔌 Adapter @@ -4394,6 +4404,59 @@ yesNo('Foo', true); // true
[⬆ Back to top](#table-of-contents) +--- + ## _Uncategorized_ + +### isArrayLike + +Checks if the provided argument is array-like (i.e. is iterable). + +Use `Array.from()` and a `try... catch` block to check if the provided argument is array-like. + +```js +const isArrayLike = arr => { + try { + Array.from(arr); + return true; + } catch (e) { + return false; + } +}; +``` + +```js +isArrayLike(document.querySelector('.className')); // true +isArrayLike('abc'); // true +isArrayLike(null); // false +``` + +
[⬆ back to top](#table-of-contents) + + +### isValidJSON + +Checks if the provided argument is a valid JSON. + +Use `JSON.parse()` and a `try... catch` block to check if the provided argument is a valid JSON. + +```js +const isValidJSON = obj => { + try { + JSON.parse(obj); + return true; + } catch (e) { + return false; + } +}; +``` + +```js +isValidJSON('{"name":"Adam","age":20}'); // true +isValidJSON('{"name":"Adam",age:"20"}'); // false +``` + +
[⬆ back to top](#table-of-contents) + ## Collaborators diff --git a/docs/index.html b/docs/index.html index 5c06dd1eb..ebbc9bc33 100644 --- a/docs/index.html +++ b/docs/index.html @@ -59,7 +59,7 @@ wrapper.appendChild(box); box.appendChild(el); }); - }

 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);
+    }

 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 ]
@@ -915,4 +915,25 @@ console.log(sdbm('age')); // 808122783
 yesNo('yes'); // true
 yesNo('No'); // false
 yesNo('Foo', true); // true
+

Uncategorized

isArrayLike

Checks if the provided argument is array-like (i.e. is iterable).

Use Array.from() and a try... catch block to check if the provided argument is array-like.

const isArrayLike = arr => {
+  try {
+    Array.from(arr);
+    return true;
+  } catch (e) {
+    return false;
+  }
+};
+
isArrayLike(document.querySelector('.className')); // true
+isArrayLike('abc'); // true
+isArrayLike(null); // false
+

isValidJSON

Checks if the provided argument is a valid JSON.

Use JSON.parse() and a try... catch block to check if the provided argument is a valid JSON.

const isValidJSON = obj => {
+  try {
+    JSON.parse(obj);
+    return true;
+  } catch (e) {
+    return false;
+  }
+};
+
isValidJSON('{"name":"Adam","age":20}'); // true
+isValidJSON('{"name":"Adam",age:"20"}'); // false
 

\ No newline at end of file diff --git a/snippets/isArrayLike.md b/snippets/isArrayLike.md index 83c8acb81..36eae12a9 100644 --- a/snippets/isArrayLike.md +++ b/snippets/isArrayLike.md @@ -6,18 +6,17 @@ Use `Array.from()` and a `try... catch` block to check if the provided argument ```js const isArrayLike = arr => { - try{ + try { Array.from(arr); return true; - } - catch(e){ + } catch (e) { return false; } -} +}; ``` ```js -isArrayLike(document.querySelector('.className')) // true -isArrayLike('abc') // true -isArrayLike(null) // false +isArrayLike(document.querySelector('.className')); // true +isArrayLike('abc'); // true +isArrayLike(null); // false ``` diff --git a/snippets/isValidJSON.md b/snippets/isValidJSON.md index 56211961b..e9898caee 100644 --- a/snippets/isValidJSON.md +++ b/snippets/isValidJSON.md @@ -6,14 +6,13 @@ Use `JSON.parse()` and a `try... catch` block to check if the provided argument ```js const isValidJSON = obj => { - try{ + try { JSON.parse(obj); return true; - } - catch(e){ + } catch (e) { return false; } -} +}; ``` ```js diff --git a/tag_database b/tag_database index e2bb75c7e..c02508fff 100644 --- a/tag_database +++ b/tag_database @@ -66,6 +66,7 @@ inRange:math intersection:array isArmstrongNumber:math isArray:utility +isArrayLike:uncategorized isBoolean:utility isDivisible:math isEven:math @@ -75,6 +76,7 @@ isNumber:utility isPrime:math isString:utility isSymbol:utility +isValidJSON:uncategorized JSONToDate:date JSONToFile:node last:array From 7b6aad54fa3ee63c726b02a2544e0f5b73d0164b Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sun, 31 Dec 2017 15:06:53 +0200 Subject: [PATCH 25/62] Update tag_database --- tag_database | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tag_database b/tag_database index c02508fff..38dc36791 100644 --- a/tag_database +++ b/tag_database @@ -66,7 +66,7 @@ inRange:math intersection:array isArmstrongNumber:math isArray:utility -isArrayLike:uncategorized +isArrayLike:utility isBoolean:utility isDivisible:math isEven:math @@ -76,7 +76,7 @@ isNumber:utility isPrime:math isString:utility isSymbol:utility -isValidJSON:uncategorized +isValidJSON:utility JSONToDate:date JSONToFile:node last:array From e59829b9efeca105b0757939447bd28a1c5c647d Mon Sep 17 00:00:00 2001 From: Rohit Tanwar <31792358+kriadmin@users.noreply.github.com> Date: Sun, 31 Dec 2017 18:38:09 +0530 Subject: [PATCH 26/62] Update isValidJSON.md --- snippets/isValidJSON.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/snippets/isValidJSON.md b/snippets/isValidJSON.md index e9898caee..76257a007 100644 --- a/snippets/isValidJSON.md +++ b/snippets/isValidJSON.md @@ -8,8 +8,10 @@ Use `JSON.parse()` and a `try... catch` block to check if the provided argument const isValidJSON = obj => { try { JSON.parse(obj); - return true; - } catch (e) { + if (o && typeof o === "object") { + return true; + } +} catch (e) { return false; } }; From f20319da0305f5b9d85cfd9bf896dc11b6b19b48 Mon Sep 17 00:00:00 2001 From: Travis CI Date: Sun, 31 Dec 2017 13:08:25 +0000 Subject: [PATCH 27/62] Travis build: 728 [ci skip] --- README.md | 126 ++++++++++++++++++++++++------------------------ docs/index.html | 44 ++++++++--------- 2 files changed, 85 insertions(+), 85 deletions(-) diff --git a/README.md b/README.md index f2b0a62bc..cb94d656d 100644 --- a/README.md +++ b/README.md @@ -244,12 +244,14 @@ * [`getType`](#gettype) * [`hexToRGB`](#hextorgb) * [`isArray`](#isarray) +* [`isArrayLike`](#isarraylike) * [`isBoolean`](#isboolean) * [`isFunction`](#isfunction) * [`isNull`](#isnull) * [`isNumber`](#isnumber) * [`isString`](#isstring) * [`isSymbol`](#issymbol) +* [`isValidJSON`](#isvalidjson) * [`randomHexColorCode`](#randomhexcolorcode) * [`RGBToHex`](#rgbtohex) * [`sdbm`](#sdbm) @@ -261,16 +263,6 @@ -### _Uncategorized_ - -
-View contents - -* [`isArrayLike`](#isarraylike) -* [`isValidJSON`](#isvalidjson) - -
- --- ## 🔌 Adapter @@ -4057,6 +4049,37 @@ isArray([1]); // true
[⬆ Back to top](#table-of-contents) +### isArrayLike + +Checks if the provided argument is array-like (i.e. is iterable). + +Use `Array.from()` and a `try... catch` block to check if the provided argument is array-like. + +```js +const isArrayLike = arr => { + try { + Array.from(arr); + return true; + } catch (e) { + return false; + } +}; +``` + +
+Examples + +```js +isArrayLike(document.querySelector('.className')); // true +isArrayLike('abc'); // true +isArrayLike(null); // false +``` + +
+ +
[⬆ Back to top](#table-of-contents) + + ### isBoolean Checks if the given argument is a native boolean element. @@ -4194,6 +4217,36 @@ isSymbol(Symbol('x')); // true
[⬆ Back to top](#table-of-contents) +### isValidJSON + +Checks if the provided argument is a valid JSON. + +Use `JSON.parse()` and a `try... catch` block to check if the provided argument is a valid JSON. + +```js +const isValidJSON = obj => { + try { + JSON.parse(obj); + return true; + } catch (e) { + return false; + } +}; +``` + +
+Examples + +```js +isValidJSON('{"name":"Adam","age":20}'); // true +isValidJSON('{"name":"Adam",age:"20"}'); // false +``` + +
+ +
[⬆ Back to top](#table-of-contents) + + ### randomHexColorCode Generates a random hexadecimal color code. @@ -4404,59 +4457,6 @@ yesNo('Foo', true); // true
[⬆ Back to top](#table-of-contents) ---- - ## _Uncategorized_ - -### isArrayLike - -Checks if the provided argument is array-like (i.e. is iterable). - -Use `Array.from()` and a `try... catch` block to check if the provided argument is array-like. - -```js -const isArrayLike = arr => { - try { - Array.from(arr); - return true; - } catch (e) { - return false; - } -}; -``` - -```js -isArrayLike(document.querySelector('.className')); // true -isArrayLike('abc'); // true -isArrayLike(null); // false -``` - -
[⬆ back to top](#table-of-contents) - - -### isValidJSON - -Checks if the provided argument is a valid JSON. - -Use `JSON.parse()` and a `try... catch` block to check if the provided argument is a valid JSON. - -```js -const isValidJSON = obj => { - try { - JSON.parse(obj); - return true; - } catch (e) { - return false; - } -}; -``` - -```js -isValidJSON('{"name":"Adam","age":20}'); // true -isValidJSON('{"name":"Adam",age:"20"}'); // false -``` - -
[⬆ back to top](#table-of-contents) - ## Collaborators diff --git a/docs/index.html b/docs/index.html index ebbc9bc33..a46afcda6 100644 --- a/docs/index.html +++ b/docs/index.html @@ -59,7 +59,7 @@ wrapper.appendChild(box); box.appendChild(el); }); - }

 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);
+    }

 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 ]
@@ -849,6 +849,17 @@ hexToRGB('#fff'); // 'rgb(255, 255, 255)'
 

isArray

Checks if the given argument is an array.

Use Array.isArray() to check if a value is classified as an array.

const isArray = val => !!val && Array.isArray(val);
 
isArray(null); // false
 isArray([1]); // true
+

isArrayLike

Checks if the provided argument is array-like (i.e. is iterable).

Use Array.from() and a try... catch block to check if the provided argument is array-like.

const isArrayLike = arr => {
+  try {
+    Array.from(arr);
+    return true;
+  } catch (e) {
+    return false;
+  }
+};
+
isArrayLike(document.querySelector('.className')); // true
+isArrayLike('abc'); // true
+isArrayLike(null); // false
 

isBoolean

Checks if the given argument is a native boolean element.

Use typeof to check if a value is classified as a boolean primitive.

const isBoolean = val => typeof val === 'boolean';
 
isBoolean(null); // false
 isBoolean(false); // true
@@ -867,6 +878,16 @@ isString('10'); // true
 

isSymbol

Checks if the given argument is a symbol.

Use typeof to check if a value is classified as a symbol primitive.

const isSymbol = val => typeof val === 'symbol';
 
isSymbol('x'); // false
 isSymbol(Symbol('x')); // true
+

isValidJSON

Checks if the provided argument is a valid JSON.

Use JSON.parse() and a try... catch block to check if the provided argument is a valid JSON.

const isValidJSON = obj => {
+  try {
+    JSON.parse(obj);
+    return true;
+  } catch (e) {
+    return false;
+  }
+};
+
isValidJSON('{"name":"Adam","age":20}'); // true
+isValidJSON('{"name":"Adam",age:"20"}'); // false
 

randomHexColorCode

Generates a random hexadecimal color code.

Use Math.random to generate a random 24-bit(6x4bits) hexadecimal number. Use bit shifting and then convert it to an hexadecimal String using toString(16).

const randomHexColorCode = () => {
   let n = ((Math.random() * 0xfffff) | 0).toString(16);
   return '#' + (n.length !== 6 ? ((Math.random() * 0xf) | 0).toString(16) + n : n);
@@ -915,25 +936,4 @@ console.log(sdbm('age')); // 808122783
 yesNo('yes'); // true
 yesNo('No'); // false
 yesNo('Foo', true); // true
-

Uncategorized

isArrayLike

Checks if the provided argument is array-like (i.e. is iterable).

Use Array.from() and a try... catch block to check if the provided argument is array-like.

const isArrayLike = arr => {
-  try {
-    Array.from(arr);
-    return true;
-  } catch (e) {
-    return false;
-  }
-};
-
isArrayLike(document.querySelector('.className')); // true
-isArrayLike('abc'); // true
-isArrayLike(null); // false
-

isValidJSON

Checks if the provided argument is a valid JSON.

Use JSON.parse() and a try... catch block to check if the provided argument is a valid JSON.

const isValidJSON = obj => {
-  try {
-    JSON.parse(obj);
-    return true;
-  } catch (e) {
-    return false;
-  }
-};
-
isValidJSON('{"name":"Adam","age":20}'); // true
-isValidJSON('{"name":"Adam",age:"20"}'); // false
 

\ No newline at end of file From 551c9b9a21cece27fa535d33c70189211bb52b10 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sun, 31 Dec 2017 15:12:16 +0200 Subject: [PATCH 28/62] Update isValidJSON.md --- snippets/isValidJSON.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/snippets/isValidJSON.md b/snippets/isValidJSON.md index 76257a007..dadefb897 100644 --- a/snippets/isValidJSON.md +++ b/snippets/isValidJSON.md @@ -2,15 +2,13 @@ Checks if the provided argument is a valid JSON. -Use `JSON.parse()` and a `try... catch` block to check if the provided argument is a valid JSON. +Use `JSON.parse()` and a `try... catch` block to check if the provided argument is a valid JSON and non-null. ```js const isValidJSON = obj => { try { JSON.parse(obj); - if (o && typeof o === "object") { - return true; - } + return !!obj; } catch (e) { return false; } From 047de7555586b9c8b05d07f61e1fea7ab2aec043 Mon Sep 17 00:00:00 2001 From: Travis CI Date: Sun, 31 Dec 2017 13:15:55 +0000 Subject: [PATCH 29/62] Travis build: 732 [ci skip] --- README.md | 29 +++++++++++++++++++++++++++-- docs/index.html | 10 +++++++--- snippets/isAbsoluteURL.md | 2 +- snippets/isValidJSON.md | 2 +- 4 files changed, 36 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index cb94d656d..477bd5b8d 100644 --- a/README.md +++ b/README.md @@ -219,6 +219,7 @@ * [`escapeHTML`](#escapehtml) * [`escapeRegExp`](#escaperegexp) * [`fromCamelCase`](#fromcamelcase) +* [`isAbsoluteURL`](#isabsoluteurl) * [`palindrome`](#palindrome) * [`repeatString`](#repeatstring) * [`reverseString`](#reversestring) @@ -3574,6 +3575,30 @@ fromCamelCase('someJavascriptProperty', '_'); // 'some_javascript_property'
[⬆ Back to top](#table-of-contents) +### isAbsoluteURL + +Returns `true` if the given string is an absolute URL, `false` otherwise. + +Use a regular expression to test if the string is an absolute URL. + +```js +const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str); +``` + +
+Examples + +```js +isAbsoluteURL('https://google.com'); // true +isAbsoluteURL('ftp://www.myserver.net'); // true +isAbsoluteURL('/foo/bar'); // false +``` + +
+ +
[⬆ Back to top](#table-of-contents) + + ### palindrome Returns `true` if the given string is a palindrome, `false` otherwise. @@ -4221,13 +4246,13 @@ isSymbol(Symbol('x')); // true Checks if the provided argument is a valid JSON. -Use `JSON.parse()` and a `try... catch` block to check if the provided argument is a valid JSON. +Use `JSON.parse()` and a `try... catch` block to check if the provided argument is a valid JSON and non-null. ```js const isValidJSON = obj => { try { JSON.parse(obj); - return true; + return !!obj; } catch (e) { return false; } diff --git a/docs/index.html b/docs/index.html index a46afcda6..fcffcb709 100644 --- a/docs/index.html +++ b/docs/index.html @@ -59,7 +59,7 @@ wrapper.appendChild(box); box.appendChild(el); }); - }

 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);
+    }

 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 ]
@@ -722,6 +722,10 @@ countVowels('gym'); // 0
 
fromCamelCase('someDatabaseFieldName', ' '); // 'some database field name'
 fromCamelCase('someLabelThatNeedsToBeCamelized', '-'); // 'some-label-that-needs-to-be-camelized'
 fromCamelCase('someJavascriptProperty', '_'); // 'some_javascript_property'
+

isAbsoluteURL

Returns true if the given string is an absolute URL, false otherwise.

Use a regular expression to test if the string is an absolute URL.

const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str);
+
isAbsoluteURL('https://google.com'); // true
+isAbsoluteURL('ftp://www.myserver.net'); // true
+isAbsoluteURL('/foo/bar'); // false
 

palindrome

Returns true if the given string is a palindrome, false otherwise.

Convert string toLowerCase() and use replace() to remove non-alphanumeric characters from it. Then, split('') into individual characters, reverse(), join('') and compare to the original, unreversed string, after converting it tolowerCase().

const palindrome = str => {
   const s = str.toLowerCase().replace(/[\W_]/g, '');
   return (
@@ -878,10 +882,10 @@ isString('10'); // true
 

isSymbol

Checks if the given argument is a symbol.

Use typeof to check if a value is classified as a symbol primitive.

const isSymbol = val => typeof val === 'symbol';
 
isSymbol('x'); // false
 isSymbol(Symbol('x')); // true
-

isValidJSON

Checks if the provided argument is a valid JSON.

Use JSON.parse() and a try... catch block to check if the provided argument is a valid JSON.

const isValidJSON = obj => {
+

isValidJSON

Checks if the provided argument is a valid JSON.

Use JSON.parse() and a try... catch block to check if the provided argument is a valid JSON and non-null.

const isValidJSON = obj => {
   try {
     JSON.parse(obj);
-    return true;
+    return !!obj;
   } catch (e) {
     return false;
   }
diff --git a/snippets/isAbsoluteURL.md b/snippets/isAbsoluteURL.md
index 8f13f5861..00d8d8936 100644
--- a/snippets/isAbsoluteURL.md
+++ b/snippets/isAbsoluteURL.md
@@ -5,7 +5,7 @@ Returns `true` if the given string is an absolute URL, `false` otherwise.
 Use a regular expression to test if the string is an absolute URL.
 
 ```js
-const isAbsoluteURL = str =>  /^[a-z][a-z0-9+.-]*:/.test(str);
+const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str);
 ```
 
 ```js
diff --git a/snippets/isValidJSON.md b/snippets/isValidJSON.md
index dadefb897..ed7672a3a 100644
--- a/snippets/isValidJSON.md
+++ b/snippets/isValidJSON.md
@@ -9,7 +9,7 @@ const isValidJSON = obj => {
   try {
     JSON.parse(obj);
     return !!obj;
-} catch (e) {
+  } catch (e) {
     return false;
   }
 };

From 2cf844ebf5fc853986512226fc07cbabf8b9e653 Mon Sep 17 00:00:00 2001
From: Angelos Chalaris 
Date: Sun, 31 Dec 2017 15:17:27 +0200
Subject: [PATCH 30/62] Update isValidJSON.md

---
 snippets/isValidJSON.md | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/snippets/isValidJSON.md b/snippets/isValidJSON.md
index ed7672a3a..5b671e67b 100644
--- a/snippets/isValidJSON.md
+++ b/snippets/isValidJSON.md
@@ -2,13 +2,13 @@
 
 Checks if the provided argument is a valid JSON.
 
-Use `JSON.parse()` and a `try... catch` block to check if the provided argument is a valid JSON and non-null.
+Use `JSON.parse()` and a `try... catch` block to check if the provided argument is a valid JSON.
 
 ```js
 const isValidJSON = obj => {
   try {
     JSON.parse(obj);
-    return !!obj;
+    return true;
   } catch (e) {
     return false;
   }
@@ -18,4 +18,5 @@ const isValidJSON = obj => {
 ```js
 isValidJSON('{"name":"Adam","age":20}'); // true
 isValidJSON('{"name":"Adam",age:"20"}'); // false
+isValidJSON(null) // true
 ```

From 0dd10dd757da5f07be38140b3563e17cc1f0ac77 Mon Sep 17 00:00:00 2001
From: Travis CI 
Date: Sun, 31 Dec 2017 13:18:31 +0000
Subject: [PATCH 31/62] Travis build: 733 [ci skip]

---
 README.md               | 5 +++--
 docs/index.html         | 5 +++--
 snippets/isValidJSON.md | 2 +-
 3 files changed, 7 insertions(+), 5 deletions(-)

diff --git a/README.md b/README.md
index 477bd5b8d..d980e1337 100644
--- a/README.md
+++ b/README.md
@@ -4246,13 +4246,13 @@ isSymbol(Symbol('x')); // true
 
 Checks if the provided argument is a valid JSON.
 
-Use `JSON.parse()` and a `try... catch` block to check if the provided argument is a valid JSON and non-null.
+Use `JSON.parse()` and a `try... catch` block to check if the provided argument is a valid JSON.
 
 ```js
 const isValidJSON = obj => {
   try {
     JSON.parse(obj);
-    return !!obj;
+    return true;
   } catch (e) {
     return false;
   }
@@ -4265,6 +4265,7 @@ const isValidJSON = obj => {
 ```js
 isValidJSON('{"name":"Adam","age":20}'); // true
 isValidJSON('{"name":"Adam",age:"20"}'); // false
+isValidJSON(null); // true
 ```
 
 
diff --git a/docs/index.html b/docs/index.html
index fcffcb709..9571d93b4 100644
--- a/docs/index.html
+++ b/docs/index.html
@@ -882,16 +882,17 @@ isString('10'); // true
 

isSymbol

Checks if the given argument is a symbol.

Use typeof to check if a value is classified as a symbol primitive.

const isSymbol = val => typeof val === 'symbol';
 
isSymbol('x'); // false
 isSymbol(Symbol('x')); // true
-

isValidJSON

Checks if the provided argument is a valid JSON.

Use JSON.parse() and a try... catch block to check if the provided argument is a valid JSON and non-null.

const isValidJSON = obj => {
+

isValidJSON

Checks if the provided argument is a valid JSON.

Use JSON.parse() and a try... catch block to check if the provided argument is a valid JSON.

const isValidJSON = obj => {
   try {
     JSON.parse(obj);
-    return !!obj;
+    return true;
   } catch (e) {
     return false;
   }
 };
 
isValidJSON('{"name":"Adam","age":20}'); // true
 isValidJSON('{"name":"Adam",age:"20"}'); // false
+isValidJSON(null); // true
 

randomHexColorCode

Generates a random hexadecimal color code.

Use Math.random to generate a random 24-bit(6x4bits) hexadecimal number. Use bit shifting and then convert it to an hexadecimal String using toString(16).

const randomHexColorCode = () => {
   let n = ((Math.random() * 0xfffff) | 0).toString(16);
   return '#' + (n.length !== 6 ? ((Math.random() * 0xf) | 0).toString(16) + n : n);
diff --git a/snippets/isValidJSON.md b/snippets/isValidJSON.md
index 5b671e67b..51b9270a2 100644
--- a/snippets/isValidJSON.md
+++ b/snippets/isValidJSON.md
@@ -18,5 +18,5 @@ const isValidJSON = obj => {
 ```js
 isValidJSON('{"name":"Adam","age":20}'); // true
 isValidJSON('{"name":"Adam",age:"20"}'); // false
-isValidJSON(null) // true
+isValidJSON(null); // true
 ```

From c46e247cf81f2047f9b895a5b353bf8b6545f4cc Mon Sep 17 00:00:00 2001
From: Travis CI 
Date: Sun, 31 Dec 2017 13:54:58 +0000
Subject: [PATCH 32/62] Travis build: 734 [ci skip]

---
 README.md                 | 32 ++++++++++++++++++++++++++++++++
 docs/index.html           | 13 ++++++++++++-
 snippets/isPromiseLike.md | 10 ++++++++--
 3 files changed, 52 insertions(+), 3 deletions(-)

diff --git a/README.md b/README.md
index d980e1337..82c18d2cf 100644
--- a/README.md
+++ b/README.md
@@ -250,6 +250,7 @@
 * [`isFunction`](#isfunction)
 * [`isNull`](#isnull)
 * [`isNumber`](#isnumber)
+* [`isPromiseLike`](#ispromiselike)
 * [`isString`](#isstring)
 * [`isSymbol`](#issymbol)
 * [`isValidJSON`](#isvalidjson)
@@ -4196,6 +4197,37 @@ isNumber(1); // true
 
[⬆ Back to top](#table-of-contents) +### isPromiseLike + +Returns `true` if an object looks like a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise), `false` otherwise. + +Check if the object is not `null`, its `typeof` matches either `object` or `function` and if it has a `.then` property, which is also a `function`. + +```js +const isPromiseLike = obj => + obj !== null && + (typeof obj === 'object' || typeof obj === 'function') && + typeof obj.then === 'function'; +``` + +
+Examples + +```js +isPromiseLike({ + then: function() { + return ''; + } +}); // true +isPromiseLike(null); // false +isPromiseLike({}); // false +``` + +
+ +
[⬆ Back to top](#table-of-contents) + + ### isString Checks if the given argument is a string. diff --git a/docs/index.html b/docs/index.html index 9571d93b4..22e389e92 100644 --- a/docs/index.html +++ b/docs/index.html @@ -59,7 +59,7 @@ wrapper.appendChild(box); box.appendChild(el); }); - }

 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);
+    }

 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 ]
@@ -876,6 +876,17 @@ isNull('null'); // false
 

isNumber

Checks if the given argument is a number.

Use typeof to check if a value is classified as a number primitive.

const isNumber = val => typeof val === 'number';
 
isNumber('1'); // false
 isNumber(1); // true
+

isPromiseLike

Returns true if an object looks like a Promise, false otherwise.

Check if the object is not null, its typeof matches either object or function and if it has a .then property, which is also a function.

const isPromiseLike = obj =>
+  obj !== null &&
+  (typeof obj === 'object' || typeof obj === 'function') &&
+  typeof obj.then === 'function';
+
isPromiseLike({
+  then: function() {
+    return '';
+  }
+}); // true
+isPromiseLike(null); // false
+isPromiseLike({}); // false
 

isString

Checks if the given argument is a string.

Use typeof to check if a value is classified as a string primitive.

const isString = val => typeof val === 'string';
 
isString(10); // false
 isString('10'); // true
diff --git a/snippets/isPromiseLike.md b/snippets/isPromiseLike.md
index d7bb9a75b..6a2ae29d4 100644
--- a/snippets/isPromiseLike.md
+++ b/snippets/isPromiseLike.md
@@ -6,11 +6,17 @@ Check if the object is not `null`, its `typeof` matches either `object` or `func
 
 ```js
 const isPromiseLike = obj =>
-  obj !== null && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
+  obj !== null &&
+  (typeof obj === 'object' || typeof obj === 'function') &&
+  typeof obj.then === 'function';
 ```
 
 ```js
-isPromiseLike({then:function () {return ''}}); // true
+isPromiseLike({
+  then: function() {
+    return '';
+  }
+}); // true
 isPromiseLike(null); // false
 isPromiseLike({}); // false
 ```

From a94d8044717d5abc084d8ede9aedef3ffc2c8537 Mon Sep 17 00:00:00 2001
From: Travis CI 
Date: Sun, 31 Dec 2017 15:16:08 +0000
Subject: [PATCH 33/62] Travis build: 740 [ci skip]

---
 README.md               | 34 ++++++++++++++++++++++++++++++++++
 docs/index.html         |  9 ++++++++-
 snippets/sortedIndex.md |  6 +++---
 tag_database            |  1 +
 4 files changed, 46 insertions(+), 4 deletions(-)

diff --git a/README.md b/README.md
index 82c18d2cf..e1864745a 100644
--- a/README.md
+++ b/README.md
@@ -265,6 +265,15 @@
 
 
 
+### _Uncategorized_
+
+
+View contents + +* [`sortedIndex`](#sortedindex) + +
+ --- ## 🔌 Adapter @@ -4515,6 +4524,31 @@ yesNo('Foo', true); // true
[⬆ Back to top](#table-of-contents) +--- + ## _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. + +```js +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; +}; +``` + +```js +sortedIndex([5, 3, 2, 1], 4); // 1 +sortedIndex([30, 50], 40); // 1 +``` + +
[⬆ back to top](#table-of-contents) + ## Collaborators diff --git a/docs/index.html b/docs/index.html index 22e389e92..c6dcd331c 100644 --- a/docs/index.html +++ b/docs/index.html @@ -59,7 +59,7 @@ wrapper.appendChild(box); box.appendChild(el); }); - }

 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);
+    }

 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 From a9ac0b40ce51b4d2403cd3040de23c0d68a5917e Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sun, 31 Dec 2017 17:18:19 +0200 Subject: [PATCH 34/62] Update isArrayLike.md --- snippets/isArrayLike.md | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/snippets/isArrayLike.md b/snippets/isArrayLike.md index 36eae12a9..ee2fc1718 100644 --- a/snippets/isArrayLike.md +++ b/snippets/isArrayLike.md @@ -2,17 +2,11 @@ Checks if the provided argument is array-like (i.e. is iterable). -Use `Array.from()` and a `try... catch` block to check if the provided argument is array-like. +Check that the object is not a function or `null` and that its `length` property is a non-negative integer below `Number.MAX_SAFE_INTEGER`. ```js -const isArrayLike = arr => { - try { - Array.from(arr); - return true; - } catch (e) { - return false; - } -}; +const isArrayLike = val => + val != null && typeof val != 'function' && val.length > -1 && val.length % 1 == 0 && val.length <= Number.MAX_SAFE_INTEGER; ``` ```js From 5869c4a78e79f0162d23c1bbf00d2d101f9e9637 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sun, 31 Dec 2017 17:19:36 +0200 Subject: [PATCH 35/62] Fixed example --- snippets/isArrayLike.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snippets/isArrayLike.md b/snippets/isArrayLike.md index ee2fc1718..051399caf 100644 --- a/snippets/isArrayLike.md +++ b/snippets/isArrayLike.md @@ -10,7 +10,7 @@ const isArrayLike = val => ``` ```js -isArrayLike(document.querySelector('.className')); // true +isArrayLike(document.querySelectorAll('.className')); // true isArrayLike('abc'); // true isArrayLike(null); // false ``` From 7f3d62a41eba2b5526bb444af8d9233dab32a4a6 Mon Sep 17 00:00:00 2001 From: Travis CI Date: Sun, 31 Dec 2017 15:49:44 +0000 Subject: [PATCH 36/62] Travis build: 743 [ci skip] --- README.md | 18 ++++++++---------- docs/index.html | 16 +++++++--------- snippets/isArrayLike.md | 8 ++++++-- 3 files changed, 21 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index e1864745a..5092802d3 100644 --- a/README.md +++ b/README.md @@ -4088,24 +4088,22 @@ isArray([1]); // true Checks if the provided argument is array-like (i.e. is iterable). -Use `Array.from()` and a `try... catch` block to check if the provided argument is array-like. +Check that the object is not a function or `null` and that its `length` property is a non-negative integer below `Number.MAX_SAFE_INTEGER`. ```js -const isArrayLike = arr => { - try { - Array.from(arr); - return true; - } catch (e) { - return false; - } -}; +const isArrayLike = val => + val != null && + typeof val != 'function' && + val.length > -1 && + val.length % 1 == 0 && + val.length <= Number.MAX_SAFE_INTEGER; ```
Examples ```js -isArrayLike(document.querySelector('.className')); // true +isArrayLike(document.querySelectorAll('.className')); // true isArrayLike('abc'); // true isArrayLike(null); // false ``` diff --git a/docs/index.html b/docs/index.html index c6dcd331c..fd4c1c019 100644 --- a/docs/index.html +++ b/docs/index.html @@ -853,15 +853,13 @@ hexToRGB('#fff'); // 'rgb(255, 255, 255)'

isArray

Checks if the given argument is an array.

Use Array.isArray() to check if a value is classified as an array.

const isArray = val => !!val && Array.isArray(val);
 
isArray(null); // false
 isArray([1]); // true
-

isArrayLike

Checks if the provided argument is array-like (i.e. is iterable).

Use Array.from() and a try... catch block to check if the provided argument is array-like.

const isArrayLike = arr => {
-  try {
-    Array.from(arr);
-    return true;
-  } catch (e) {
-    return false;
-  }
-};
-
isArrayLike(document.querySelector('.className')); // true
+

isArrayLike

Checks if the provided argument is array-like (i.e. is iterable).

Check that the object is not a function or null and that its length property is a non-negative integer below Number.MAX_SAFE_INTEGER.

const isArrayLike = val =>
+  val != null &&
+  typeof val != 'function' &&
+  val.length > -1 &&
+  val.length % 1 == 0 &&
+  val.length <= Number.MAX_SAFE_INTEGER;
+
isArrayLike(document.querySelectorAll('.className')); // true
 isArrayLike('abc'); // true
 isArrayLike(null); // false
 

isBoolean

Checks if the given argument is a native boolean element.

Use typeof to check if a value is classified as a boolean primitive.

const isBoolean = val => typeof val === 'boolean';
diff --git a/snippets/isArrayLike.md b/snippets/isArrayLike.md
index 051399caf..8d846e68f 100644
--- a/snippets/isArrayLike.md
+++ b/snippets/isArrayLike.md
@@ -5,8 +5,12 @@ Checks if the provided argument is array-like (i.e. is iterable).
 Check that the object is not a function or `null` and that its `length` property is a non-negative integer below `Number.MAX_SAFE_INTEGER`.
 
 ```js
-const isArrayLike = val => 
-  val != null && typeof val != 'function' && val.length > -1 && val.length % 1 == 0 && val.length <= Number.MAX_SAFE_INTEGER;
+const isArrayLike = val =>
+  val != null &&
+  typeof val != 'function' &&
+  val.length > -1 &&
+  val.length % 1 == 0 &&
+  val.length <= Number.MAX_SAFE_INTEGER;
 ```
 
 ```js

From e65707fea3115b5a47cc610850aef20efe4306eb Mon Sep 17 00:00:00 2001
From: Pl4gue 
Date: Sun, 31 Dec 2017 17:20:13 +0100
Subject: [PATCH 37/62] Remove unused spans

---
 docs/mini/flavor.scss         | 2 +-
 static-parts/index-start.html | 2 --
 2 files changed, 1 insertion(+), 3 deletions(-)

diff --git a/docs/mini/flavor.scss b/docs/mini/flavor.scss
index 13f369a30..e1a957cb1 100644
--- a/docs/mini/flavor.scss
+++ b/docs/mini/flavor.scss
@@ -121,7 +121,7 @@ code {
   transform: scale(1);  /* Deals with the issue described in #243 */
 }
 pre { font-size: 1rem; border: 0.0625rem solid var(--secondary-border-color); border-radius: var(--universal-border-radius);}
-.group{position:relative;margin-top:2em;margin-bottom:-1em}
+.group{position:relative;margin-top:2em;margin-bottom:1em}
 .search{font-size:14px;margin-top:-.1em;display:block;width:100%;border:none;border-bottom:1px solid var(--nav-link-color)}
 .search:focus{outline:none}
 label#search-label{color:var(--nav-link-color);font-size:18px;font-weight:400;position:absolute;left:5px;top:10px}
diff --git a/static-parts/index-start.html b/static-parts/index-start.html
index 2dd7839c9..0dfd76c9d 100644
--- a/static-parts/index-start.html
+++ b/static-parts/index-start.html
@@ -92,8 +92,6 @@