From 0e3c7d754bfe9c44dc9bcb2acbc6dfd3badfa71c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20Feje=C5=A1?= Date: Thu, 21 Dec 2017 19:13:15 +0100 Subject: [PATCH 01/11] fix typo --- static-parts/README-start.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/static-parts/README-start.md b/static-parts/README-start.md index ae6f9909a..a053e0e85 100644 --- a/static-parts/README-start.md +++ b/static-parts/README-start.md @@ -1,7 +1,7 @@ ![Logo](/logo.png) # 30 seconds of code [![Gitter chat](https://badges.gitter.im/gitterHQ/gitter.png)](https://gitter.im/30-seconds-of-code/Lobby) [![Travis Build](https://travis-ci.org/Chalarangelo/30-seconds-of-code.svg?branch=master)](https://travis-ci.org/Chalarangelo/30-seconds-of-code) -> Curated collection of useful Javascript snippets that you can understand in 30 seconds or less. +> Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less. - Use Ctrl + F or command + F to search for a snippet. - Contributions welcome, please read the [contribution guide](CONTRIBUTING.md). From 5dd03ba8ed7552a80b5306f91e7f237e12d8294f Mon Sep 17 00:00:00 2001 From: Y_Less Date: Thu, 21 Dec 2017 18:19:39 +0000 Subject: [PATCH 02/11] Fix #299 --- snippets/everyNth.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/snippets/everyNth.md b/snippets/everyNth.md index 0c79e3a1f..f326ebe2b 100644 --- a/snippets/everyNth.md +++ b/snippets/everyNth.md @@ -5,6 +5,6 @@ Returns every nth element in an array. Use `Array.filter()` to create a new array that contains every nth element of a given array. ```js -const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === 0); -// everyNth([1,2,3,4,5,6], 2) -> [ 1, 3, 5 ] +const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1); +// everyNth([1,2,3,4,5,6], 2) -> [ 2, 4, 6 ] ``` From 4bf5e36c9d49ef296b6413f8b5e41d8ed69e89fd Mon Sep 17 00:00:00 2001 From: Y_Less Date: Thu, 21 Dec 2017 18:20:59 +0000 Subject: [PATCH 03/11] Remove validateEmail entirely (#294). --- snippets/validateEmail.md | 12 ------------ 1 file changed, 12 deletions(-) delete mode 100644 snippets/validateEmail.md diff --git a/snippets/validateEmail.md b/snippets/validateEmail.md deleted file mode 100644 index cb5588474..000000000 --- a/snippets/validateEmail.md +++ /dev/null @@ -1,12 +0,0 @@ -### validateEmail - -Returns `true` if the given string is a valid email, `false` otherwise. - -Use a regular expression to check if the email is valid. -Returns `true` if email is valid, `false` if not. - -```js -const validateEmail = str => - /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(str); -// validateEmail(mymail@gmail.com) -> true -``` From 4469d198376d6896f36de79e7734e9135adf5152 Mon Sep 17 00:00:00 2001 From: Pl4gue Date: Thu, 21 Dec 2017 18:33:03 +0000 Subject: [PATCH 04/11] Travis build: 57 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index abb50682e..f190eb242 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ ![Logo](/logo.png) # 30 seconds of code [![Gitter chat](https://badges.gitter.im/gitterHQ/gitter.png)](https://gitter.im/30-seconds-of-code/Lobby) [![Travis Build](https://travis-ci.org/Chalarangelo/30-seconds-of-code.svg?branch=master)](https://travis-ci.org/Chalarangelo/30-seconds-of-code) -> Curated collection of useful Javascript snippets that you can understand in 30 seconds or less. +> Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less. - Use Ctrl + F or command + F to search for a snippet. - Contributions welcome, please read the [contribution guide](CONTRIBUTING.md). From e9ab8af825ad3c5d4635581355eac21374bf3fc9 Mon Sep 17 00:00:00 2001 From: Pl4gue Date: Thu, 21 Dec 2017 18:35:12 +0000 Subject: [PATCH 05/11] Travis build: 58 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f190eb242..abb50682e 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ ![Logo](/logo.png) # 30 seconds of code [![Gitter chat](https://badges.gitter.im/gitterHQ/gitter.png)](https://gitter.im/30-seconds-of-code/Lobby) [![Travis Build](https://travis-ci.org/Chalarangelo/30-seconds-of-code.svg?branch=master)](https://travis-ci.org/Chalarangelo/30-seconds-of-code) -> Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less. +> Curated collection of useful Javascript snippets that you can understand in 30 seconds or less. - Use Ctrl + F or command + F to search for a snippet. - Contributions welcome, please read the [contribution guide](CONTRIBUTING.md). From ecaf146aee1df45d39cb9efb0612b1739e0391b2 Mon Sep 17 00:00:00 2001 From: Pl4gue Date: Thu, 21 Dec 2017 18:36:58 +0000 Subject: [PATCH 06/11] Travis build: 60 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index abb50682e..f190eb242 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ ![Logo](/logo.png) # 30 seconds of code [![Gitter chat](https://badges.gitter.im/gitterHQ/gitter.png)](https://gitter.im/30-seconds-of-code/Lobby) [![Travis Build](https://travis-ci.org/Chalarangelo/30-seconds-of-code.svg?branch=master)](https://travis-ci.org/Chalarangelo/30-seconds-of-code) -> Curated collection of useful Javascript snippets that you can understand in 30 seconds or less. +> Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less. - Use Ctrl + F or command + F to search for a snippet. - Contributions welcome, please read the [contribution guide](CONTRIBUTING.md). From 22dbda940ff524a8d48c0311a656fc4968ad247c Mon Sep 17 00:00:00 2001 From: Rob Taussig Date: Thu, 21 Dec 2017 13:55:25 -0500 Subject: [PATCH 07/11] Removed unique occurence of wrapping a single argument function with parenthesis --- README.md | 2 +- snippets/compact.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f190eb242..67489521b 100644 --- a/README.md +++ b/README.md @@ -243,7 +243,7 @@ Removes falsey values from an array. Use `Array.filter()` to filter out falsey values (`false`, `null`, `0`, `""`, `undefined`, and `NaN`). ```js -const compact = (arr) => arr.filter(Boolean); +const compact = arr => arr.filter(Boolean); // compact([0, 1, false, 2, '', 3, 'a', 'e'*23, NaN, 's', 34]) -> [ 1, 2, 3, 'a', 's', 34 ] ``` diff --git a/snippets/compact.md b/snippets/compact.md index c63796719..d09160afe 100644 --- a/snippets/compact.md +++ b/snippets/compact.md @@ -5,6 +5,6 @@ Removes falsey values from an array. Use `Array.filter()` to filter out falsey values (`false`, `null`, `0`, `""`, `undefined`, and `NaN`). ```js -const compact = (arr) => arr.filter(Boolean); +const compact = arr => arr.filter(Boolean); // compact([0, 1, false, 2, '', 3, 'a', 'e'*23, NaN, 's', 34]) -> [ 1, 2, 3, 'a', 's', 34 ] ``` From e06cbd9e60a561d4a5bb6cec3dc9bbd567676cc1 Mon Sep 17 00:00:00 2001 From: Pl4gue Date: Thu, 21 Dec 2017 19:08:21 +0000 Subject: [PATCH 08/11] Travis build: 63 --- docs/index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/index.html b/docs/index.html index ef88e9600..5ce2df18c 100644 --- a/docs/index.html +++ b/docs/index.html @@ -234,7 +234,7 @@ If the original array can't be split evenly, the final chunk will contain the re

compact

Removes falsey values from an array.

Use Array.filter() to filter out falsey values (false, null, 0, "", undefined, and NaN).

-
const compact = (arr) => arr.filter(Boolean);
+
const compact = arr => arr.filter(Boolean);
 // compact([0, 1, false, 2, '', 3, 'a', 'e'*23, NaN, 's', 34]) -> [ 1, 2, 3, 'a', 's', 34 ]
 

countOccurrences

From b20c958154c8e400086b15c26747a757bbb7debc Mon Sep 17 00:00:00 2001 From: Pl4gue Date: Thu, 21 Dec 2017 21:15:50 +0000 Subject: [PATCH 09/11] Travis build: 66 --- README.md | 20 ++------------------ docs/index.html | 13 ++----------- tag_database | 1 - 3 files changed, 4 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index 67489521b..33e21e537 100644 --- a/README.md +++ b/README.md @@ -154,7 +154,6 @@ * [`toDecimalMark`](#todecimalmark) * [`toOrdinalSuffix`](#toordinalsuffix) * [`UUIDGenerator`](#uuidgenerator) -* [`validateEmail`](#validateemail) * [`validateNumber`](#validatenumber) ## Array @@ -355,8 +354,8 @@ Returns every nth element in an array. Use `Array.filter()` to create a new array that contains every nth element of a given array. ```js -const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === 0); -// everyNth([1,2,3,4,5,6], 2) -> [ 1, 3, 5 ] +const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1); +// everyNth([1,2,3,4,5,6], 2) -> [ 2, 4, 6 ] ``` [⬆ back to top](#table-of-contents) @@ -2167,21 +2166,6 @@ const UUIDGenerator = () => [⬆ back to top](#table-of-contents) -### validateEmail - -Returns `true` if the given string is a valid email, `false` otherwise. - -Use a regular expression to check if the email is valid. -Returns `true` if email is valid, `false` if not. - -```js -const validateEmail = str => - /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(str); -// validateEmail(mymail@gmail.com) -> true -``` - -[⬆ back to top](#table-of-contents) - ### validateNumber Returns `true` if the given value is a number, `false` otherwise. diff --git a/docs/index.html b/docs/index.html index 5ce2df18c..3b1a8b42c 100644 --- a/docs/index.html +++ b/docs/index.html @@ -185,7 +185,6 @@ toDecimalMark toOrdinalSuffix UUIDGenerator -validateEmail validateNumber
 

Array

@@ -290,8 +289,8 @@ Returns the remaining elements.


everyNth

Returns every nth element in an array.

Use Array.filter() to create a new array that contains every nth element of a given array.

-
const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === 0);
-// everyNth([1,2,3,4,5,6], 2) -> [ 1, 3, 5 ]
+
const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1);
+// everyNth([1,2,3,4,5,6], 2) -> [ 2, 4, 6 ]
 

filterNonUnique

Filters out the non-unique values in an array.

@@ -1318,14 +1317,6 @@ If digit is found in teens pattern, use teens ordinal.

); // UUIDGenerator() -> '7982fcfe-5721-4632-bede-6000885be57d'
-

validateEmail

-

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

-

Use a regular expression to check if the email is valid. -Returns true if email is valid, false if not.

-
const validateEmail = str =>
-  /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(str);
-// validateEmail(mymail@gmail.com) -> true
-

validateNumber

Returns true if the given value is a number, false otherwise.

Use !isNaN in combination with parseFloat() to check if the argument is a number. diff --git a/tag_database b/tag_database index 6e965bf45..78da7daaf 100644 --- a/tag_database +++ b/tag_database @@ -119,7 +119,6 @@ truncateString:string truthCheckCollection:object union:array UUIDGenerator:utility -validateEmail:utility validateNumber:utility without:array words:string From 0b90492a41c85b8aa159cf5cbe8442190f9c0fad Mon Sep 17 00:00:00 2001 From: Yuchen Zhang Date: Thu, 21 Dec 2017 17:31:51 -0500 Subject: [PATCH 10/11] Improve isPrime to be O(sqrt(n)) (#298) * improve isPrime to be O(sqrt(n)) --- README.md | 41 ++++++++++++++++++++--------------------- snippets/isPrime.md | 5 ++--- 2 files changed, 22 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index 33e21e537..665dfded9 100644 --- a/README.md +++ b/README.md @@ -184,7 +184,7 @@ Use `Array.reduce()` and the `lcm` formula (uses recursion) to calculate the low ```js const arrayLcm = arr =>{ const gcd = (x, y) => !y ? x : gcd(y, x % y); - const lcm = (x, y) => (x*y)/gcd(x, y) + const lcm = (x, y) => (x*y)/gcd(x, y) return arr.reduce((a,b) => lcm(a,b)); } // arrayLcm([1,2,3,4,5]) -> 60 @@ -468,7 +468,7 @@ Use `Array((end + 1) - start)` to create an array of the desired length, `Array. You can omit `start` to use a default value of `0`. ```js -const initializeArrayWithRange = (end, start = 0) => +const initializeArrayWithRange = (end, start = 0) => Array.from({ length: (end + 1) - start }).map((v, i) => i + start); // initializeArrayWithRange(5) -> [0,1,2,3,4,5] // initializeArrayWithRange(7, 3) -> [3,4,5,6,7] @@ -523,7 +523,7 @@ Maps the values of an array to an object using a function, where the key-value p Use an anonymous inner function scope to declare an undefined memory space, using closures to store a return value. Use a new `Array` to stor the array with a map of the function over its data set and a comma operator to return a second step, without needing to move from one context to another (due to closures and order of operations). ```js -const mapObject = (arr, fn) => +const mapObject = (arr, fn) => (a => (a = [arr, arr.map(fn)], a[0].reduce( (acc,val,ind) => (acc[val] = a[1][ind], acc), {}) )) ( ); /* const squareIt = arr => mapObject(arr, a => a*a) @@ -576,7 +576,7 @@ _(For a snippet that does not mutate the original array see [`without`](#without const pull = (arr, ...args) => { let argState = Array.isArray(args[0]) ? args[0] : args; let pulled = arr.filter((v, i) => !argState.includes(v)); - arr.length = 0; + arr.length = 0; pulled.forEach(v => arr.push(v)); }; @@ -597,14 +597,14 @@ Mutates the original array to filter out the values at the specified indexes. Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed. Use `Array.length = 0` to mutate the passed in array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values. -Use `Array.push()` to keep track of pulled values +Use `Array.push()` to keep track of pulled values ```js const pullAtIndex = (arr, pullArr) => { let removed = []; let pulled = arr.map((v, i) => pullArr.includes(i) ? removed.push(v) : v) .filter((v, i) => !pullArr.includes(i)) - arr.length = 0; + arr.length = 0; pulled.forEach(v => arr.push(v)); return removed; } @@ -624,11 +624,11 @@ Mutates the original array to filter out the values specified. Returns the remov Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed. Use `Array.length = 0` to mutate the passed in array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values. -Use `Array.push()` to keep track of pulled values +Use `Array.push()` to keep track of pulled values ```js const pullAtValue = (arr, pullArr) => { - let removed = [], + let removed = [], pushToRemove = arr.forEach((v, i) => pullArr.includes(v) ? removed.push(v) : v), mutateTo = arr.filter((v, i) => !pullArr.includes(v)); arr.length = 0; @@ -1193,14 +1193,14 @@ const arraySum = arr => arr.reduce((acc, val) => acc + val, 0); Clamps `num` within the inclusive `lower` and `upper` bounds. -If `lower` is greater than `upper`, swap them. -If `num` falls within the range, return `num`. +If `lower` is greater than `upper`, swap them. +If `num` falls within the range, return `num`. Otherwise return the nearest number in the range. ```js const clampNumber = (num, lower, upper) => { if(lower > upper) upper = [lower, lower = upper][0]; - return (num>=lower && num<=upper) ? num : ((num < lower) ? lower : upper) + return (num>=lower && num<=upper) ? num : ((num < lower) ? lower : upper) } // clampNumber(2, 3, 5) -> 3 // clampNumber(1, -1, -5) -> -1 @@ -1315,7 +1315,7 @@ const hammingDistance = (num1, num2) => ### inRange -Checks if the given number falls in the given range. +Checks if the given number falls in the given range. Use arithmetic comparison to check if the given number is in the specified range. If the second parameter, `end`, is not specified, the reange is considered to be from `0` to `start`. @@ -1340,7 +1340,7 @@ Checks if the given number is an armstrong number or not. Convert the given number into array of digits. Use `Math.pow()` to get the appropriate power for each digit and sum them up. If the sum is equal to the number itself, return `true` otherwise `false`. ```js -const isArmstrongNumber = digits => +const isArmstrongNumber = digits => ( arr => arr.reduce( ( a, d ) => a + Math.pow( parseInt( d ), arr.length ), 0 ) == digits ? true : false )( ( digits+'' ).split( '' ) ); // isArmstrongNumber(1634) -> true // isArmstrongNumber(371) -> true @@ -1384,7 +1384,7 @@ Returns `false` if the provided number has positive divisors other than 1 and it ```js const isPrime = num => { - for (var i = 2; i < num; i++) if (num % i == 0) return false; + for (var i = 2; i * i <= num; i++) if (num % i == 0) return false; return num >= 2; } // isPrime(11) -> true @@ -1474,7 +1474,7 @@ const powerset = arr => [⬆ back to top](#table-of-contents) -### primes +### primes Generates primes up to a given number, using the Sieve of Eratosthenes. @@ -1482,13 +1482,13 @@ Generate an array from `2` to the given number. Use `Array.filter()` to filter o ```js const primes = num => { - let arr = Array.from({length:num-1}).map((x,i)=> i+2), + let arr = Array.from({length:num-1}).map((x,i)=> i+2), sqroot = Math.floor(Math.sqrt(num)), numsTillSqroot = Array.from({length:sqroot-1}).map((x,i)=> i+2); numsTillSqroot.forEach(x => arr = arr.filter(y => ((y%x)!==0)||(y==x))); - return arr; + return arr; } -// primes(10) -> [2,3,5,7] +// primes(10) -> [2,3,5,7] ``` [⬆ back to top](#table-of-contents) @@ -1735,7 +1735,7 @@ a === b -> false Checks if the predicate (second argument) is truthy on all elements of a collection (first argument). Use `Array.every()` to check if each passed object has the specified property and if it returns a truthy value. - + ```js const truthCheckCollection = (collection, pre) => (collection.every(obj => obj[pre])); // truthCheckCollection([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}], "sex") -> true @@ -2118,7 +2118,7 @@ Use `toString()` to convert the float `num` to a string, then use regex to separ ```js const toDecimalMark = (num) => { - let cleanNum = num.toString().split('').filter(n => '0123456789.'.includes(n)).join('') + let cleanNum = num.toString().split('').filter(n => '0123456789.'.includes(n)).join('') let wholeNum = cleanNum.split('.')[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") let decNum = `.${cleanNum.split('.')[1]}` return wholeNum + decNum; @@ -2184,4 +2184,3 @@ const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == ## 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/).* - diff --git a/snippets/isPrime.md b/snippets/isPrime.md index cc1f69b14..0a2157e2f 100644 --- a/snippets/isPrime.md +++ b/snippets/isPrime.md @@ -6,10 +6,9 @@ Returns `false` if the provided number has positive divisors other than 1 and it ```js const isPrime = num => { - for (var i = 2; i < num; i++) if (num % i == 0) return false; + for (var i = 2; i * i <= num; i++) if (num % i == 0) return false; return num >= 2; -} +}; // isPrime(11) -> true // isPrime(12) -> false -// isPrime(1) -> false ``` From ac1a10f0391dade9f2ce94140eb1a5d49e506ccf Mon Sep 17 00:00:00 2001 From: Pl4gue Date: Thu, 21 Dec 2017 22:33:38 +0000 Subject: [PATCH 11/11] Travis build: 69 --- README.md | 42 +++++++++++++++++++++--------------------- docs/index.html | 5 ++--- 2 files changed, 23 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index 665dfded9..3a5d20676 100644 --- a/README.md +++ b/README.md @@ -184,7 +184,7 @@ Use `Array.reduce()` and the `lcm` formula (uses recursion) to calculate the low ```js const arrayLcm = arr =>{ const gcd = (x, y) => !y ? x : gcd(y, x % y); - const lcm = (x, y) => (x*y)/gcd(x, y) + const lcm = (x, y) => (x*y)/gcd(x, y) return arr.reduce((a,b) => lcm(a,b)); } // arrayLcm([1,2,3,4,5]) -> 60 @@ -468,7 +468,7 @@ Use `Array((end + 1) - start)` to create an array of the desired length, `Array. You can omit `start` to use a default value of `0`. ```js -const initializeArrayWithRange = (end, start = 0) => +const initializeArrayWithRange = (end, start = 0) => Array.from({ length: (end + 1) - start }).map((v, i) => i + start); // initializeArrayWithRange(5) -> [0,1,2,3,4,5] // initializeArrayWithRange(7, 3) -> [3,4,5,6,7] @@ -523,7 +523,7 @@ Maps the values of an array to an object using a function, where the key-value p Use an anonymous inner function scope to declare an undefined memory space, using closures to store a return value. Use a new `Array` to stor the array with a map of the function over its data set and a comma operator to return a second step, without needing to move from one context to another (due to closures and order of operations). ```js -const mapObject = (arr, fn) => +const mapObject = (arr, fn) => (a => (a = [arr, arr.map(fn)], a[0].reduce( (acc,val,ind) => (acc[val] = a[1][ind], acc), {}) )) ( ); /* const squareIt = arr => mapObject(arr, a => a*a) @@ -576,7 +576,7 @@ _(For a snippet that does not mutate the original array see [`without`](#without const pull = (arr, ...args) => { let argState = Array.isArray(args[0]) ? args[0] : args; let pulled = arr.filter((v, i) => !argState.includes(v)); - arr.length = 0; + arr.length = 0; pulled.forEach(v => arr.push(v)); }; @@ -597,14 +597,14 @@ Mutates the original array to filter out the values at the specified indexes. Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed. Use `Array.length = 0` to mutate the passed in array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values. -Use `Array.push()` to keep track of pulled values +Use `Array.push()` to keep track of pulled values ```js const pullAtIndex = (arr, pullArr) => { let removed = []; let pulled = arr.map((v, i) => pullArr.includes(i) ? removed.push(v) : v) .filter((v, i) => !pullArr.includes(i)) - arr.length = 0; + arr.length = 0; pulled.forEach(v => arr.push(v)); return removed; } @@ -624,11 +624,11 @@ Mutates the original array to filter out the values specified. Returns the remov Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed. Use `Array.length = 0` to mutate the passed in array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values. -Use `Array.push()` to keep track of pulled values +Use `Array.push()` to keep track of pulled values ```js const pullAtValue = (arr, pullArr) => { - let removed = [], + let removed = [], pushToRemove = arr.forEach((v, i) => pullArr.includes(v) ? removed.push(v) : v), mutateTo = arr.filter((v, i) => !pullArr.includes(v)); arr.length = 0; @@ -1193,14 +1193,14 @@ const arraySum = arr => arr.reduce((acc, val) => acc + val, 0); Clamps `num` within the inclusive `lower` and `upper` bounds. -If `lower` is greater than `upper`, swap them. -If `num` falls within the range, return `num`. +If `lower` is greater than `upper`, swap them. +If `num` falls within the range, return `num`. Otherwise return the nearest number in the range. ```js const clampNumber = (num, lower, upper) => { if(lower > upper) upper = [lower, lower = upper][0]; - return (num>=lower && num<=upper) ? num : ((num < lower) ? lower : upper) + return (num>=lower && num<=upper) ? num : ((num < lower) ? lower : upper) } // clampNumber(2, 3, 5) -> 3 // clampNumber(1, -1, -5) -> -1 @@ -1315,7 +1315,7 @@ const hammingDistance = (num1, num2) => ### inRange -Checks if the given number falls in the given range. +Checks if the given number falls in the given range. Use arithmetic comparison to check if the given number is in the specified range. If the second parameter, `end`, is not specified, the reange is considered to be from `0` to `start`. @@ -1340,7 +1340,7 @@ Checks if the given number is an armstrong number or not. Convert the given number into array of digits. Use `Math.pow()` to get the appropriate power for each digit and sum them up. If the sum is equal to the number itself, return `true` otherwise `false`. ```js -const isArmstrongNumber = digits => +const isArmstrongNumber = digits => ( arr => arr.reduce( ( a, d ) => a + Math.pow( parseInt( d ), arr.length ), 0 ) == digits ? true : false )( ( digits+'' ).split( '' ) ); // isArmstrongNumber(1634) -> true // isArmstrongNumber(371) -> true @@ -1386,10 +1386,9 @@ Returns `false` if the provided number has positive divisors other than 1 and it const isPrime = num => { for (var i = 2; i * i <= num; i++) if (num % i == 0) return false; return num >= 2; -} +}; // isPrime(11) -> true // isPrime(12) -> false -// isPrime(1) -> false ``` [⬆ back to top](#table-of-contents) @@ -1474,7 +1473,7 @@ const powerset = arr => [⬆ back to top](#table-of-contents) -### primes +### primes Generates primes up to a given number, using the Sieve of Eratosthenes. @@ -1482,13 +1481,13 @@ Generate an array from `2` to the given number. Use `Array.filter()` to filter o ```js const primes = num => { - let arr = Array.from({length:num-1}).map((x,i)=> i+2), + let arr = Array.from({length:num-1}).map((x,i)=> i+2), sqroot = Math.floor(Math.sqrt(num)), numsTillSqroot = Array.from({length:sqroot-1}).map((x,i)=> i+2); numsTillSqroot.forEach(x => arr = arr.filter(y => ((y%x)!==0)||(y==x))); - return arr; + return arr; } -// primes(10) -> [2,3,5,7] +// primes(10) -> [2,3,5,7] ``` [⬆ back to top](#table-of-contents) @@ -1735,7 +1734,7 @@ a === b -> false Checks if the predicate (second argument) is truthy on all elements of a collection (first argument). Use `Array.every()` to check if each passed object has the specified property and if it returns a truthy value. - + ```js const truthCheckCollection = (collection, pre) => (collection.every(obj => obj[pre])); // truthCheckCollection([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}], "sex") -> true @@ -2118,7 +2117,7 @@ Use `toString()` to convert the float `num` to a string, then use regex to separ ```js const toDecimalMark = (num) => { - let cleanNum = num.toString().split('').filter(n => '0123456789.'.includes(n)).join('') + let cleanNum = num.toString().split('').filter(n => '0123456789.'.includes(n)).join('') let wholeNum = cleanNum.split('.')[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") let decNum = `.${cleanNum.split('.')[1]}` return wholeNum + decNum; @@ -2184,3 +2183,4 @@ const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == ## 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/).* + diff --git a/docs/index.html b/docs/index.html index 3b1a8b42c..b3aaf2cd5 100644 --- a/docs/index.html +++ b/docs/index.html @@ -868,12 +868,11 @@ Returns true if the number is even, false if the numbe

Checks if the provided integer is a prime number.

Returns false if the provided number has positive divisors other than 1 and itself or if the number itself is less than 2.

const isPrime = num => {
-  for (var i = 2; i < num; i++) if (num % i == 0) return false;
+  for (var i = 2; i * i <= num; i++) if (num % i == 0) return false;
   return num >= 2;
-}
+};
 // isPrime(11) -> true
 // isPrime(12) -> false
-// isPrime(1) -> false
 

lcm

Returns the least common multiple of two numbers.