From 0c7bffb81c4874d3ae616e5a5515bfc4030060a5 Mon Sep 17 00:00:00 2001 From: b117020 Date: Fri, 15 Dec 2017 01:07:31 +0530 Subject: [PATCH 01/49] method name --- snippets/current method name.txt | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 snippets/current method name.txt diff --git a/snippets/current method name.txt b/snippets/current method name.txt new file mode 100644 index 000000000..7f76c176d --- /dev/null +++ b/snippets/current method name.txt @@ -0,0 +1,3 @@ +###code to view name of current method + +String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); From 7f0fc22cca009c08d01992617e159f8b11762e97 Mon Sep 17 00:00:00 2001 From: xaveyaguarez Date: Thu, 14 Dec 2017 23:51:01 -0800 Subject: [PATCH 02/49] added symmetric difference note to Array difference --- snippets/array-difference.md | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/snippets/array-difference.md b/snippets/array-difference.md index 208cb811e..b70c2d837 100644 --- a/snippets/array-difference.md +++ b/snippets/array-difference.md @@ -3,6 +3,14 @@ Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values not contained in `b`. ```js -const difference = (a, b) => { const s = new Set(b); return a.filter(x => !s.has(x)); }; -// difference([1,2,3], [1,2]) -> [3] +const difference = (a, b) => { const s = new Set(b); a.filter(x => !s.has(x)); }; +// difference([1,2,3], [1,2,4]) -> [3] +``` + +This function can also be used to generate the symmetric difference or disjunctive union by swapping the +arrays and combining the results. + +```js +const symmetricDifference = (a, b) => [...difference(a,b), ...difference(b,a)]; +// difference([1,2,3], [1,2,4]) -> [3,4] ``` From 67f9684f800fcdfe407eee938d233bb1a22bce52 Mon Sep 17 00:00:00 2001 From: iamsoorena Date: Fri, 15 Dec 2017 23:16:18 +0330 Subject: [PATCH 03/49] add description to array includes snippet since it looks a lot like es6 native includes function. --- snippets/array-includes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/snippets/array-includes.md b/snippets/array-includes.md index 5ebcbc009..16fa578a5 100644 --- a/snippets/array-includes.md +++ b/snippets/array-includes.md @@ -3,6 +3,7 @@ Use `slice()` to offset the array/string and `indexOf()` to check if the value is included. Omit the last argument, `fromIndex`, to check the whole array/string. +In [ES6](http://www.ecma-international.org/ecma-262/7.0/#sec-array.prototype.includes), you can use a similar native `.includes()` function. ```js const includes = (collection, val, fromIndex=0) => collection.slice(fromIndex).indexOf(val) != -1; // includes("30-seconds-of-code", "code") -> true From fcac67cbd9f7c6f5316e2ea4f02a467d09bee089 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sat, 16 Dec 2017 14:32:16 +0200 Subject: [PATCH 04/49] Tag and build --- README.md | 15 +++++++++++++++ tag_database | 1 + 2 files changed, 16 insertions(+) diff --git a/README.md b/README.md index c15a1a0cb..64dc81117 100644 --- a/README.md +++ b/README.md @@ -116,6 +116,7 @@ * [Is number](#is-number) * [Is string](#is-string) * [Is symbol](#is-symbol) +* [JSON to date](#json-to-date) * [Measure time taken by function](#measure-time-taken-by-function) * [Number to array of digits](#number-to-array-of-digits) * [Ordinal suffix of number](#ordinal-suffix-of-number) @@ -1311,6 +1312,20 @@ const isSymbol = val => typeof val === 'symbol'; [⬆ back to top](#table-of-contents) +### JSON to date + +Use `Date()`, to convert dates in JSON format to readable format (`dd/mm/yyyy`). + +```js +const jsonToDate = arr => { + const dt = new Date(parseInt(arr.toString().substr(6))); + return `${ dt.getDate() }/${ dt.getMonth() + 1 }/${ dt.getFullYear() }` +}; +// jsonToDate(/Date(1489525200000)/) -> "14/3/2017" +``` + +[⬆ back to top](#table-of-contents) + ### Measure time taken by function Use `console.time()` and `console.timeEnd()` to measure the difference between the start and end times to determine how long the callback took to execute. diff --git a/tag_database b/tag_database index 9f1b18f46..05dc761bd 100644 --- a/tag_database +++ b/tag_database @@ -55,6 +55,7 @@ is-function:utility is-number:utility is-string:utility is-symbol:utility +JSON-to-date:utility last-of-list:array measure-time-taken-by-function:utility median-of-array-of-numbers:array From ce58ba64a292de4def3b09e95da4172b53126a32 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sat, 16 Dec 2017 14:34:40 +0200 Subject: [PATCH 05/49] Removed array includes snippet (native JS alternative exists) --- README.md | 14 -------------- snippets/array-includes.md | 11 ----------- tag_database | 1 - 3 files changed, 26 deletions(-) delete mode 100644 snippets/array-includes.md diff --git a/README.md b/README.md index 64dc81117..2304d2f04 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,6 @@ ### Array * [Array concatenation](#array-concatenation) * [Array difference](#array-difference) -* [Array includes](#array-includes) * [Array intersection](#array-intersection) * [Array remove](#array-remove) * [Array sample](#array-sample) @@ -153,19 +152,6 @@ const difference = (a, b) => { const s = new Set(b); return a.filter(x => !s.has [⬆ back to top](#table-of-contents) -### Array includes - -Use `slice()` to offset the array/string and `indexOf()` to check if the value is included. -Omit the last argument, `fromIndex`, to check the whole array/string. - -```js -const includes = (collection, val, fromIndex=0) => collection.slice(fromIndex).indexOf(val) != -1; -// includes("30-seconds-of-code", "code") -> true -// includes([1, 2, 3, 4], [1, 2], 1) -> false -``` - -[⬆ back to top](#table-of-contents) - ### Array intersection Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values contained in `b`. diff --git a/snippets/array-includes.md b/snippets/array-includes.md deleted file mode 100644 index 16fa578a5..000000000 --- a/snippets/array-includes.md +++ /dev/null @@ -1,11 +0,0 @@ -### Array includes - -Use `slice()` to offset the array/string and `indexOf()` to check if the value is included. -Omit the last argument, `fromIndex`, to check the whole array/string. - -In [ES6](http://www.ecma-international.org/ecma-262/7.0/#sec-array.prototype.includes), you can use a similar native `.includes()` function. -```js -const includes = (collection, val, fromIndex=0) => collection.slice(fromIndex).indexOf(val) != -1; -// includes("30-seconds-of-code", "code") -> true -// includes([1, 2, 3, 4], [1, 2], 1) -> false -``` diff --git a/tag_database b/tag_database index 05dc761bd..bd508483b 100644 --- a/tag_database +++ b/tag_database @@ -2,7 +2,6 @@ anagrams-of-string-(with-duplicates):string array-concatenation:array array-difference:array -array-includes:array array-intersection:array array-remove:array array-sample:array From c75deefbf34e06d04a429b85a63b70c52679a255 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sat, 16 Dec 2017 14:37:45 +0200 Subject: [PATCH 06/49] Update and rename current method name.txt to log-method-name.md --- snippets/current method name.txt | 3 --- snippets/log-method-name.md | 8 ++++++++ 2 files changed, 8 insertions(+), 3 deletions(-) delete mode 100644 snippets/current method name.txt create mode 100644 snippets/log-method-name.md diff --git a/snippets/current method name.txt b/snippets/current method name.txt deleted file mode 100644 index 7f76c176d..000000000 --- a/snippets/current method name.txt +++ /dev/null @@ -1,3 +0,0 @@ -###code to view name of current method - -String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); diff --git a/snippets/log-method-name.md b/snippets/log-method-name.md new file mode 100644 index 000000000..d8922ee62 --- /dev/null +++ b/snippets/log-method-name.md @@ -0,0 +1,8 @@ +### Log method name + +Use `console.debug()` and the `name` property of the passed method to log the method's name to the `debug` channel of the console. + +```js +const methodName = fn => (console.debug(fn.name), fn); +// methodName(methodName) -> methodName (logged in debug channel of console) +``` From 5eaacd506e48c7cc87d3d02905269f30df2c9f4f Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sat, 16 Dec 2017 14:39:08 +0200 Subject: [PATCH 07/49] Tag and build --- README.md | 12 ++++++++++++ snippets/log-function-name.md | 8 ++++++++ snippets/log-method-name.md | 8 -------- tag_database | 1 + 4 files changed, 21 insertions(+), 8 deletions(-) create mode 100644 snippets/log-function-name.md delete mode 100644 snippets/log-method-name.md diff --git a/README.md b/README.md index 2304d2f04..babf49a07 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,7 @@ * [Chain asynchronous functions](#chain-asynchronous-functions) * [Compose functions](#compose-functions) * [Curry](#curry) +* [Log function name](#log-function-name) * [Pipe functions](#pipe-functions) * [Promisify](#promisify) * [Run promises in series](#run-promises-in-series) @@ -743,6 +744,17 @@ const curry = (fn, arity = fn.length, ...args) => [⬆ back to top](#table-of-contents) +### Log function name + +Use `console.debug()` and the `name` property of the passed method to log the method's name to the `debug` channel of the console. + +```js +const functionName = fn => (console.debug(fn.name), fn); +// functionName(Math.max) -> max (logged in debug channel of console) +``` + +[⬆ back to top](#table-of-contents) + ### Pipe functions Use `Array.reduce()` with the spread operator (`...`) to perform left-to-right function composition. diff --git a/snippets/log-function-name.md b/snippets/log-function-name.md new file mode 100644 index 000000000..b449331f8 --- /dev/null +++ b/snippets/log-function-name.md @@ -0,0 +1,8 @@ +### Log function name + +Use `console.debug()` and the `name` property of the passed method to log the method's name to the `debug` channel of the console. + +```js +const functionName = fn => (console.debug(fn.name), fn); +// functionName(Math.max) -> max (logged in debug channel of console) +``` diff --git a/snippets/log-method-name.md b/snippets/log-method-name.md deleted file mode 100644 index d8922ee62..000000000 --- a/snippets/log-method-name.md +++ /dev/null @@ -1,8 +0,0 @@ -### Log method name - -Use `console.debug()` and the `name` property of the passed method to log the method's name to the `debug` channel of the console. - -```js -const methodName = fn => (console.debug(fn.name), fn); -// methodName(methodName) -> methodName (logged in debug channel of console) -``` diff --git a/tag_database b/tag_database index bd508483b..3999b7f30 100644 --- a/tag_database +++ b/tag_database @@ -56,6 +56,7 @@ is-string:utility is-symbol:utility JSON-to-date:utility last-of-list:array +log-function-name:function measure-time-taken-by-function:utility median-of-array-of-numbers:array nth-element-of-array:array From ec407bae9147ec2bb33353dd3d0b9cdec8c49cdb Mon Sep 17 00:00:00 2001 From: gnipbao Date: Sat, 16 Dec 2017 21:24:29 +0800 Subject: [PATCH 08/49] add camelize and decamelize. --- snippets/camelize.md | 17 +++++++++++++++++ snippets/decamelize.md | 16 ++++++++++++++++ tag_database | 2 ++ 3 files changed, 35 insertions(+) create mode 100644 snippets/camelize.md create mode 100644 snippets/decamelize.md diff --git a/snippets/camelize.md b/snippets/camelize.md new file mode 100644 index 000000000..937a974e8 --- /dev/null +++ b/snippets/camelize.md @@ -0,0 +1,17 @@ +### Camelize + +Camelize a string, cutting the string by multiple separators like + hyphens, underscores and spaces. + +```js +/** + * @param {str} string str to camelize + * @return string Camelized text + */ +const camelize = str => str.replace(/^([A-Z])|[\s-_]+(\w)/g, + (match, p1, p2, offset) => p2 ? p2.toUpperCase() : p1.toLowerCase()); +// camelize("some_database_field_name") -> 'someDatabaseFieldName' +// camelize("Some label that needs to be camelized") -> 'someLabelThatNeedsToBeCamelized' +// camelize("some-javascript-property") -> 'someJavascriptProperty' +// camelize("some-mixed_string with spaces_underscores-and-hyphens") -> 'someMixedStringWithSpacesUnderscoresAndHyphens' +``` diff --git a/snippets/decamelize.md b/snippets/decamelize.md new file mode 100644 index 000000000..ab5ac6fa7 --- /dev/null +++ b/snippets/decamelize.md @@ -0,0 +1,16 @@ +### decamelize + +Decamelizes a string with/without a custom separator (underscore by default). + +```js +const decamelize = (str, separator) => { + separator = typeof separator === 'undefined' ? '_' : separator; + return str + .replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2') + .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2') + .toLowerCase(); +} +// decamelize('someDatabaseFieldName', ' ') -> 'some database field name' +// decamelize('someLabelThatNeedsToBeCamelized', '-') -> 'some-label-that-needs-to-be-camelized' +// decamelize('someJavascriptProperty', '_') -> 'some_javascript_property' +``` diff --git a/tag_database b/tag_database index b2535a484..aed0ec9d8 100644 --- a/tag_database +++ b/tag_database @@ -5,6 +5,7 @@ array-intersection:array array-union:array average-of-array-of-numbers:array bottom-visible:browser +camelize:string capitalize-first-letter-of-every-word:string capitalize-first-letter:string chain-asynchronous-functions:function @@ -15,6 +16,7 @@ compact:array count-occurrences-of-a-value-in-array:array current-URL:browser curry:function +decamelize:string deep-flatten-array:array distance-between-two-points:math divisible-by-number:math From 3e770710c720f1acfcd2e0dbd1b0fbb84257b741 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sat, 16 Dec 2017 17:11:49 +0200 Subject: [PATCH 09/49] Update and rename camelize.md to convert-string-to-camelcase.md --- .../{camelize.md => convert-string-to-camelcase.md} | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) rename snippets/{camelize.md => convert-string-to-camelcase.md} (52%) diff --git a/snippets/camelize.md b/snippets/convert-string-to-camelcase.md similarity index 52% rename from snippets/camelize.md rename to snippets/convert-string-to-camelcase.md index 937a974e8..ba34a6835 100644 --- a/snippets/camelize.md +++ b/snippets/convert-string-to-camelcase.md @@ -1,15 +1,10 @@ -### Camelize +### Convert string to camelcase -Camelize a string, cutting the string by multiple separators like - hyphens, underscores and spaces. +Use `replace()` to remove underscores, hyphens and spaces and convert words to camelcase. ```js -/** - * @param {str} string str to camelize - * @return string Camelized text - */ -const camelize = str => str.replace(/^([A-Z])|[\s-_]+(\w)/g, - (match, p1, p2, offset) => p2 ? p2.toUpperCase() : p1.toLowerCase()); +const toCamelCase = str => + str.replace(/^([A-Z])|[\s-_]+(\w)/g, (match, p1, p2, offset) => p2 ? p2.toUpperCase() : p1.toLowerCase()); // camelize("some_database_field_name") -> 'someDatabaseFieldName' // camelize("Some label that needs to be camelized") -> 'someLabelThatNeedsToBeCamelized' // camelize("some-javascript-property") -> 'someJavascriptProperty' From 8c2423138450e6c5bd8ab1345ae6d70d337d3153 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sat, 16 Dec 2017 17:14:16 +0200 Subject: [PATCH 10/49] Update and rename decamelize.md to convert-string-from-camelcase.md --- snippets/convert-string-from-camelcase.md | 13 +++++++++++++ snippets/decamelize.md | 16 ---------------- 2 files changed, 13 insertions(+), 16 deletions(-) create mode 100644 snippets/convert-string-from-camelcase.md delete mode 100644 snippets/decamelize.md diff --git a/snippets/convert-string-from-camelcase.md b/snippets/convert-string-from-camelcase.md new file mode 100644 index 000000000..969be904d --- /dev/null +++ b/snippets/convert-string-from-camelcase.md @@ -0,0 +1,13 @@ +### Convert string from camelcase + +Use `replace()` to remove underscores, hyphens and spaces and convert words to camelcase. +Omit the scond argument to use a default separator of '_'. + +```js +const fromCamelCase = (str, separator = '_') => + str.replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2') + .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2').toLowerCase(); +// decamelize('someDatabaseFieldName', ' ') -> 'some database field name' +// decamelize('someLabelThatNeedsToBeCamelized', '-') -> 'some-label-that-needs-to-be-camelized' +// decamelize('someJavascriptProperty', '_') -> 'some_javascript_property' +``` diff --git a/snippets/decamelize.md b/snippets/decamelize.md deleted file mode 100644 index ab5ac6fa7..000000000 --- a/snippets/decamelize.md +++ /dev/null @@ -1,16 +0,0 @@ -### decamelize - -Decamelizes a string with/without a custom separator (underscore by default). - -```js -const decamelize = (str, separator) => { - separator = typeof separator === 'undefined' ? '_' : separator; - return str - .replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2') - .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2') - .toLowerCase(); -} -// decamelize('someDatabaseFieldName', ' ') -> 'some database field name' -// decamelize('someLabelThatNeedsToBeCamelized', '-') -> 'some-label-that-needs-to-be-camelized' -// decamelize('someJavascriptProperty', '_') -> 'some_javascript_property' -``` From b236f39dfa5399e90292e5c308204116704b8322 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sat, 16 Dec 2017 17:14:45 +0200 Subject: [PATCH 11/49] Update tag_database --- tag_database | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tag_database b/tag_database index aed0ec9d8..458604576 100644 --- a/tag_database +++ b/tag_database @@ -5,7 +5,7 @@ array-intersection:array array-union:array average-of-array-of-numbers:array bottom-visible:browser -camelize:string +convert-string-to-camelcase:string capitalize-first-letter-of-every-word:string capitalize-first-letter:string chain-asynchronous-functions:function @@ -16,7 +16,7 @@ compact:array count-occurrences-of-a-value-in-array:array current-URL:browser curry:function -decamelize:string +convert-string-from-camelcase:string deep-flatten-array:array distance-between-two-points:math divisible-by-number:math From b55b684931b02ac781d9a95adaa16f9abda2fac3 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sat, 16 Dec 2017 17:19:16 +0200 Subject: [PATCH 12/49] Build, resolve #172 --- CONTRIBUTING.md | 1 + README.md | 35 ++++++++++++++++++++++++++++++++++- scripts/lint-script.js | 1 + snippets/array-remove.md | 2 +- tag_database | 4 ++-- 5 files changed, 39 insertions(+), 4 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 40e6f2a17..37b9cc767 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -29,6 +29,7 @@ Here's what you can do to help: - Try to keep your snippets' code short and to the point. Use modern techniques and features. Make sure to test your code before submitting. - All snippets must be followed by one (more if necessary) test case after the code, on a new line, in the form of a comment, along with the expected output. The syntax for this is `myFunction('testInput') -> 'testOutput'`. Use multiline comments only if necessary. - Try to make your function name unique, so that it does not conflict with existing snippets. + - Snippet functions do not have to handle errors in input, unless it's necessary (e.g. a mathematical function that cannot be extended to negative numbers should handle negative input appropriately). - Snippets should be short (usually below 10 lines). If your snippet is longer than that, you can still submit it, and we can help you shorten it or figure out ways to improve it. - Snippets *should* solve real-world problems, no matter how simple. - Snippets *should* be abstract enough to be applied to different scenarios. diff --git a/README.md b/README.md index babf49a07..357c4b642 100644 --- a/README.md +++ b/README.md @@ -101,6 +101,8 @@ * [Capitalize first letter of every word](#capitalize-first-letter-of-every-word) * [Capitalize first letter](#capitalize-first-letter) * [Check for palindrome](#check-for-palindrome) +* [Convert string from camelcase](#convert-string-from-camelcase) +* [Convert string to camelcase](#convert-string-to-camelcase) * [Reverse a string](#reverse-a-string) * [Sort characters in string (alphabetical)](#sort-characters-in-string-alphabetical) * [Truncate a string](#truncate-a-string) @@ -175,7 +177,7 @@ const remove = (arr, func) => arr.splice(arr.indexOf(val), 1); return acc.concat(val); }, []) : []; -//remove([1, 2, 3, 4], n => n % 2 == 0) -> [2, 4] +// remove([1, 2, 3, 4], n => n % 2 == 0) -> [2, 4] ``` [⬆ back to top](#table-of-contents) @@ -1152,6 +1154,37 @@ const palindrome = str => { [⬆ back to top](#table-of-contents) +### Convert string from camelcase + +Use `replace()` to remove underscores, hyphens and spaces and convert words to camelcase. +Omit the scond argument to use a default separator of '_'. + +```js +const fromCamelCase = (str, separator = '_') => + str.replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2') + .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2').toLowerCase(); +// decamelize('someDatabaseFieldName', ' ') -> 'some database field name' +// decamelize('someLabelThatNeedsToBeCamelized', '-') -> 'some-label-that-needs-to-be-camelized' +// decamelize('someJavascriptProperty', '_') -> 'some_javascript_property' +``` + +[⬆ back to top](#table-of-contents) + +### Convert string to camelcase + +Use `replace()` to remove underscores, hyphens and spaces and convert words to camelcase. + +```js +const toCamelCase = str => + str.replace(/^([A-Z])|[\s-_]+(\w)/g, (match, p1, p2, offset) => p2 ? p2.toUpperCase() : p1.toLowerCase()); +// camelize("some_database_field_name") -> 'someDatabaseFieldName' +// camelize("Some label that needs to be camelized") -> 'someLabelThatNeedsToBeCamelized' +// camelize("some-javascript-property") -> 'someJavascriptProperty' +// camelize("some-mixed_string with spaces_underscores-and-hyphens") -> 'someMixedStringWithSpacesUnderscoresAndHyphens' +``` + +[⬆ back to top](#table-of-contents) + ### Reverse a string Use array destructuring and `Array.reverse()` to reverse the order of the characters in the string. diff --git a/scripts/lint-script.js b/scripts/lint-script.js index 5d6d8721e..4aaa7c240 100644 --- a/scripts/lint-script.js +++ b/scripts/lint-script.js @@ -1,6 +1,7 @@ /* This is the linter script that lints snippets. Run using `npm run linter`. + You might have to run `npm i -g semistandard` for this script to run properly. */ // Load modules const fs = require('fs-extra'), cp = require('child_process'), path = require('path'), chalk = require('chalk'); diff --git a/snippets/array-remove.md b/snippets/array-remove.md index e08a4a02f..df2a83867 100644 --- a/snippets/array-remove.md +++ b/snippets/array-remove.md @@ -9,5 +9,5 @@ const remove = (arr, func) => arr.splice(arr.indexOf(val), 1); return acc.concat(val); }, []) : []; -//remove([1, 2, 3, 4], n => n % 2 == 0) -> [2, 4] +// remove([1, 2, 3, 4], n => n % 2 == 0) -> [2, 4] ``` diff --git a/tag_database b/tag_database index 927d17274..8181032df 100644 --- a/tag_database +++ b/tag_database @@ -10,7 +10,6 @@ array-without:array array-zip:array average-of-array-of-numbers:array bottom-visible:browser -convert-string-to-camelcase:string capitalize-first-letter-of-every-word:string capitalize-first-letter:string chain-asynchronous-functions:function @@ -20,10 +19,11 @@ clean-JSON-object:object collatz-algorithm:math compact:array compose-functions:function +convert-string-from-camelcase:string +convert-string-to-camelcase:string count-occurrences-of-a-value-in-array:array current-URL:browser curry:function -convert-string-from-camelcase:string deep-flatten-array:array distance-between-two-points:math divisible-by-number:math From ef8771127c20ea141351dc1b862c796061707820 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sat, 16 Dec 2017 17:38:06 +0200 Subject: [PATCH 13/49] Remove array concat --- README.md | 12 ------------ snippets/array-concatenation.md | 8 -------- tag_database | 1 - 3 files changed, 21 deletions(-) delete mode 100644 snippets/array-concatenation.md diff --git a/README.md b/README.md index 357c4b642..123ea24f1 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,6 @@ ## Table of Contents ### Array -* [Array concatenation](#array-concatenation) * [Array difference](#array-difference) * [Array intersection](#array-intersection) * [Array remove](#array-remove) @@ -133,17 +132,6 @@ ## Array -### Array concatenation - -Use Array spread operators (`...`) to concatenate an array with any additional arrays and/or values, specified in `args`. - -```js -const ArrayConcat = (arr, ...args) => [...arr,...args]; -// ArrayConcat([1], [1, 2, 3, [4]]) -> [1, 1, 2, 3, [4]] -``` - -[⬆ back to top](#table-of-contents) - ### Array difference Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values not contained in `b`. diff --git a/snippets/array-concatenation.md b/snippets/array-concatenation.md deleted file mode 100644 index 4c337c9e9..000000000 --- a/snippets/array-concatenation.md +++ /dev/null @@ -1,8 +0,0 @@ -### Array concatenation - -Use Array spread operators (`...`) to concatenate an array with any additional arrays and/or values, specified in `args`. - -```js -const ArrayConcat = (arr, ...args) => [...arr,...args]; -// ArrayConcat([1], [1, 2, 3, [4]]) -> [1, 1, 2, 3, [4]] -``` diff --git a/tag_database b/tag_database index 8181032df..ac64d168d 100644 --- a/tag_database +++ b/tag_database @@ -1,6 +1,5 @@ 3-digit-hexcode-to-6-digit-hexcode:utility anagrams-of-string-(with-duplicates):string -array-concatenation:array array-difference:array array-intersection:array array-remove:array From ba8c1ccbc45ce40fefc4662d6b1c848c1076c2c0 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sat, 16 Dec 2017 18:00:42 +0200 Subject: [PATCH 14/49] Tag and build --- README.md | 78 ++++++++++++++++++++++++++-------------------------- tag_database | 6 ++-- 2 files changed, 42 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index 123ea24f1..35808040d 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,7 @@ ### Date * [Get days difference between dates](#get-days-difference-between-dates) +* [JSON to date](#json-to-date) ### Function * [Chain asynchronous functions](#chain-asynchronous-functions) @@ -79,6 +80,8 @@ * [Hamming distance](#hamming-distance) * [Percentile](#percentile) * [Powerset](#powerset) +* [Random integer in range](#random-integer-in-range) +* [Random number in range](#random-number-in-range) * [Round number to n digits](#round-number-to-n-digits) * [Standard deviation](#standard-deviation) @@ -117,12 +120,9 @@ * [Is number](#is-number) * [Is string](#is-string) * [Is symbol](#is-symbol) -* [JSON to date](#json-to-date) * [Measure time taken by function](#measure-time-taken-by-function) * [Number to array of digits](#number-to-array-of-digits) * [Ordinal suffix of number](#ordinal-suffix-of-number) -* [Random integer in range](#random-integer-in-range) -* [Random number in range](#random-number-in-range) * [RGB to hexadecimal](#rgb-to-hexadecimal) * [URL parameters](#url-parameters) * [UUID generator](#uuid-generator) @@ -680,6 +680,20 @@ const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateIni // getDaysDiffBetweenDates(new Date("2017-12-13"), new Date("2017-12-22")) -> 9 ``` +[⬆ back to top](#table-of-contents) + +### JSON to date + +Use `Date()`, to convert dates in JSON format to readable format (`dd/mm/yyyy`). + +```js +const jsonToDate = arr => { + const dt = new Date(parseInt(arr.toString().substr(6))); + return `${ dt.getDate() }/${ dt.getMonth() + 1 }/${ dt.getFullYear() }` +}; +// jsonToDate(/Date(1489525200000)/) -> "14/3/2017" +``` + [⬆ back to top](#table-of-contents) ## Function @@ -935,6 +949,28 @@ const powerset = arr => [⬆ back to top](#table-of-contents) +### Random integer in range + +Use `Math.random()` to generate a random number and map it to the desired range, using `Math.floor()` to make it an integer. + +```js +const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; +// randomIntegerInRange(0, 5) -> 2 +``` + +[⬆ back to top](#table-of-contents) + +### Random number in range + +Use `Math.random()` to generate a random value, map it to the desired range using multiplication. + +```js +const randomInRange = (min, max) => Math.random() * (max - min) + min; +// randomInRange(2,10) -> 6.0211363285087005 +``` + +[⬆ back to top](#table-of-contents) + ### Round number to n digits Use `Math.round()` and template literals to round the number to the specified number of digits. @@ -1331,20 +1367,6 @@ const isSymbol = val => typeof val === 'symbol'; [⬆ back to top](#table-of-contents) -### JSON to date - -Use `Date()`, to convert dates in JSON format to readable format (`dd/mm/yyyy`). - -```js -const jsonToDate = arr => { - const dt = new Date(parseInt(arr.toString().substr(6))); - return `${ dt.getDate() }/${ dt.getMonth() + 1 }/${ dt.getFullYear() }` -}; -// jsonToDate(/Date(1489525200000)/) -> "14/3/2017" -``` - -[⬆ back to top](#table-of-contents) - ### Measure time taken by function Use `console.time()` and `console.timeEnd()` to measure the difference between the start and end times to determine how long the callback took to execute. @@ -1392,28 +1414,6 @@ const toOrdinalSuffix = num => { [⬆ back to top](#table-of-contents) -### Random integer in range - -Use `Math.random()` to generate a random number and map it to the desired range, using `Math.floor()` to make it an integer. - -```js -const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; -// randomIntegerInRange(0, 5) -> 2 -``` - -[⬆ back to top](#table-of-contents) - -### Random number in range - -Use `Math.random()` to generate a random value, map it to the desired range using multiplication. - -```js -const randomInRange = (min, max) => Math.random() * (max - min) + min; -// randomInRange(2,10) -> 6.0211363285087005 -``` - -[⬆ back to top](#table-of-contents) - ### RGB to hexadecimal Convert given RGB parameters to hexadecimal string using bitwise left-shift operator (`<<`) and `toString(16)`, then `padStart(6,'0')` to get a 6-digit hexadecimal value. diff --git a/tag_database b/tag_database index ac64d168d..88532ea9f 100644 --- a/tag_database +++ b/tag_database @@ -55,7 +55,7 @@ is-function:utility is-number:utility is-string:utility is-symbol:utility -JSON-to-date:utility +JSON-to-date:date last-of-list:array log-function-name:function measure-time-taken-by-function:utility @@ -70,8 +70,8 @@ pick:array pipe-functions:function powerset:math promisify:function -random-integer-in-range:utility -random-number-in-range:utility +random-integer-in-range:math +random-number-in-range:math read-file-as-array-of-lines:node redirect-to-URL:browser reverse-a-string:string From 8f5aa15b3fbf76fdceee4cc9fbf7acb62ac99d66 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sat, 16 Dec 2017 18:01:59 +0200 Subject: [PATCH 15/49] Remove valueOrDefault --- README.md | 12 ------------ snippets/value-or-default.md | 8 -------- tag_database | 1 - 3 files changed, 21 deletions(-) delete mode 100644 snippets/value-or-default.md diff --git a/README.md b/README.md index 35808040d..b88fd06c3 100644 --- a/README.md +++ b/README.md @@ -128,7 +128,6 @@ * [UUID generator](#uuid-generator) * [Validate email](#validate-email) * [Validate number](#validate-number) -* [Value or default](#value-or-default) ## Array @@ -1480,17 +1479,6 @@ const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == [⬆ back to top](#table-of-contents) -### Value or default - -Returns value, or default value if passed value is `falsy`. - -```js -const valueOrDefault = (value, d) => value || d; -// valueOrDefault(NaN, 30) -> 30 -``` - -[⬆ back to top](#table-of-contents) - ## 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/value-or-default.md b/snippets/value-or-default.md deleted file mode 100644 index 0af9529e8..000000000 --- a/snippets/value-or-default.md +++ /dev/null @@ -1,8 +0,0 @@ -### Value or default - -Returns value, or default value if passed value is `falsy`. - -```js -const valueOrDefault = (value, d) => value || d; -// valueOrDefault(NaN, 30) -> 30 -``` diff --git a/tag_database b/tag_database index 88532ea9f..c833e4f81 100644 --- a/tag_database +++ b/tag_database @@ -97,5 +97,4 @@ URL-parameters:utility UUID-generator:utility validate-email:utility validate-number:utility -value-or-default:utility write-JSON-to-file:node From 7895d9f519fd6471543c0bd0231cf9bcc3ff7592 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sat, 16 Dec 2017 18:40:38 +0200 Subject: [PATCH 16/49] Added symmetric difference as its own snippet, resolve #168 --- README.md | 17 ++++++++++++++++- snippets/array-difference.md | 10 +--------- snippets/array-symmetric-difference.md | 11 +++++++++++ tag_database | 1 + 4 files changed, 29 insertions(+), 10 deletions(-) create mode 100644 snippets/array-symmetric-difference.md diff --git a/README.md b/README.md index b88fd06c3..af82b8f36 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ * [Array intersection](#array-intersection) * [Array remove](#array-remove) * [Array sample](#array-sample) +* [Array symmetric difference](#array-symmetric-difference) * [Array union](#array-union) * [Array without](#array-without) * [Array zip](#array-zip) @@ -137,7 +138,7 @@ Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values no ```js const difference = (a, b) => { const s = new Set(b); return a.filter(x => !s.has(x)); }; -// difference([1,2,3], [1,2]) -> [3] +// difference([1,2,3], [1,2,4]) -> [3] ``` [⬆ back to top](#table-of-contents) @@ -181,6 +182,20 @@ const sample = arr => arr[Math.floor(Math.random() * arr.length)]; [⬆ back to top](#table-of-contents) +### Array symmetric difference + +Create a `Set` from each array, then use `Array.filter()` on each of them to only keep values not contained in the other. + +```js +const symmetricDifference = (a, b) => { + const sA = new Set(a), sB = new Set(b); + return [...a.filter(x => !sB.has(x)), ...b.filter(x => !sA.has(x))]; +} +// symmetricDifference([1,2,3], [1,2,4]) -> [3,4] +``` + +[⬆ back to top](#table-of-contents) + ### Array union Create a `Set` with all values of `a` and `b` and convert to an array. diff --git a/snippets/array-difference.md b/snippets/array-difference.md index b70c2d837..defd82d6f 100644 --- a/snippets/array-difference.md +++ b/snippets/array-difference.md @@ -3,14 +3,6 @@ Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values not contained in `b`. ```js -const difference = (a, b) => { const s = new Set(b); a.filter(x => !s.has(x)); }; +const difference = (a, b) => { const s = new Set(b); return a.filter(x => !s.has(x)); }; // difference([1,2,3], [1,2,4]) -> [3] ``` - -This function can also be used to generate the symmetric difference or disjunctive union by swapping the -arrays and combining the results. - -```js -const symmetricDifference = (a, b) => [...difference(a,b), ...difference(b,a)]; -// difference([1,2,3], [1,2,4]) -> [3,4] -``` diff --git a/snippets/array-symmetric-difference.md b/snippets/array-symmetric-difference.md new file mode 100644 index 000000000..7d178cd15 --- /dev/null +++ b/snippets/array-symmetric-difference.md @@ -0,0 +1,11 @@ +### Array symmetric difference + +Create a `Set` from each array, then use `Array.filter()` on each of them to only keep values not contained in the other. + +```js +const symmetricDifference = (a, b) => { + const sA = new Set(a), sB = new Set(b); + return [...a.filter(x => !sB.has(x)), ...b.filter(x => !sA.has(x))]; +} +// symmetricDifference([1,2,3], [1,2,4]) -> [3,4] +``` diff --git a/tag_database b/tag_database index c833e4f81..6cce617ea 100644 --- a/tag_database +++ b/tag_database @@ -4,6 +4,7 @@ array-difference:array array-intersection:array array-remove:array array-sample:array +array-symmetric-difference:array array-union:array array-without:array array-zip:array From 52776a01a8817e2831ddadc3856bc068f33fd12b Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sat, 16 Dec 2017 19:02:23 +0200 Subject: [PATCH 17/49] Resolve #156 --- README.md | 5 ++++- snippets/factorial.md | 5 ++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index af82b8f36..0d015fbee 100644 --- a/README.md +++ b/README.md @@ -891,9 +891,12 @@ const isEven = num => num % 2 === 0; Use recursion. If `n` is less than or equal to `1`, return `1`. Otherwise, return the product of `n` and the factorial of `n - 1`. +Throws an exception if `n` is a negative number. ```js -const factorial = n => n <= 1 ? 1 : n * factorial(n - 1); +const factorial = n => + n < 0 ? (() => { throw new TypeError('Negative numbers are not allowed!') })() + : n <= 1 ? 1 : n * factorial(n - 1); // factorial(6) -> 720 ``` diff --git a/snippets/factorial.md b/snippets/factorial.md index 155b7229e..d881fe941 100644 --- a/snippets/factorial.md +++ b/snippets/factorial.md @@ -3,8 +3,11 @@ Use recursion. If `n` is less than or equal to `1`, return `1`. Otherwise, return the product of `n` and the factorial of `n - 1`. +Throws an exception if `n` is a negative number. ```js -const factorial = n => n <= 1 ? 1 : n * factorial(n - 1); +const factorial = n => + n < 0 ? (() => { throw new TypeError('Negative numbers are not allowed!') })() + : n <= 1 ? 1 : n * factorial(n - 1); // factorial(6) -> 720 ``` From da68c19cb40ed380fe81d462e2a3cd25a9c32af8 Mon Sep 17 00:00:00 2001 From: Alexander Sokolov Date: Sat, 16 Dec 2017 22:08:02 +0300 Subject: [PATCH 18/49] Update convert-string-from-camelcase.md --- snippets/convert-string-from-camelcase.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/snippets/convert-string-from-camelcase.md b/snippets/convert-string-from-camelcase.md index 969be904d..d9f2bacd6 100644 --- a/snippets/convert-string-from-camelcase.md +++ b/snippets/convert-string-from-camelcase.md @@ -7,7 +7,7 @@ Omit the scond argument to use a default separator of '_'. const fromCamelCase = (str, separator = '_') => str.replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2') .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2').toLowerCase(); -// decamelize('someDatabaseFieldName', ' ') -> 'some database field name' -// decamelize('someLabelThatNeedsToBeCamelized', '-') -> 'some-label-that-needs-to-be-camelized' -// decamelize('someJavascriptProperty', '_') -> 'some_javascript_property' +// fromCamelCase('someDatabaseFieldName', ' ') -> 'some database field name' +// fromCamelCase('someLabelThatNeedsToBeCamelized', '-') -> 'some-label-that-needs-to-be-camelized' +// fromCamelCase('someJavascriptProperty', '_') -> 'some_javascript_property' ``` From d84e4f0a3f0f8781b5eaf8ced83963ceabe01a38 Mon Sep 17 00:00:00 2001 From: Alexander Sokolov Date: Sat, 16 Dec 2017 22:09:06 +0300 Subject: [PATCH 19/49] Update convert-string-to-camelcase.md --- snippets/convert-string-to-camelcase.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/snippets/convert-string-to-camelcase.md b/snippets/convert-string-to-camelcase.md index ba34a6835..f59d213ae 100644 --- a/snippets/convert-string-to-camelcase.md +++ b/snippets/convert-string-to-camelcase.md @@ -5,8 +5,8 @@ Use `replace()` to remove underscores, hyphens and spaces and convert words to c ```js const toCamelCase = str => str.replace(/^([A-Z])|[\s-_]+(\w)/g, (match, p1, p2, offset) => p2 ? p2.toUpperCase() : p1.toLowerCase()); -// camelize("some_database_field_name") -> 'someDatabaseFieldName' -// camelize("Some label that needs to be camelized") -> 'someLabelThatNeedsToBeCamelized' -// camelize("some-javascript-property") -> 'someJavascriptProperty' -// camelize("some-mixed_string with spaces_underscores-and-hyphens") -> 'someMixedStringWithSpacesUnderscoresAndHyphens' +// toCamelCase("some_database_field_name") -> 'someDatabaseFieldName' +// toCamelCase("Some label that needs to be camelized") -> 'someLabelThatNeedsToBeCamelized' +// toCamelCase("some-javascript-property") -> 'someJavascriptProperty' +// toCamelCase("some-mixed_string with spaces_underscores-and-hyphens") -> 'someMixedStringWithSpacesUnderscoresAndHyphens' ``` From 84fc01a7219230ba8fc53ff6c8f7bf1a0872cd11 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sat, 16 Dec 2017 21:17:28 +0200 Subject: [PATCH 20/49] Build --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 0d015fbee..bb968c164 100644 --- a/README.md +++ b/README.md @@ -1204,9 +1204,9 @@ Omit the scond argument to use a default separator of '_'. const fromCamelCase = (str, separator = '_') => str.replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2') .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2').toLowerCase(); -// decamelize('someDatabaseFieldName', ' ') -> 'some database field name' -// decamelize('someLabelThatNeedsToBeCamelized', '-') -> 'some-label-that-needs-to-be-camelized' -// decamelize('someJavascriptProperty', '_') -> 'some_javascript_property' +// fromCamelCase('someDatabaseFieldName', ' ') -> 'some database field name' +// fromCamelCase('someLabelThatNeedsToBeCamelized', '-') -> 'some-label-that-needs-to-be-camelized' +// fromCamelCase('someJavascriptProperty', '_') -> 'some_javascript_property' ``` [⬆ back to top](#table-of-contents) @@ -1218,10 +1218,10 @@ Use `replace()` to remove underscores, hyphens and spaces and convert words to c ```js const toCamelCase = str => str.replace(/^([A-Z])|[\s-_]+(\w)/g, (match, p1, p2, offset) => p2 ? p2.toUpperCase() : p1.toLowerCase()); -// camelize("some_database_field_name") -> 'someDatabaseFieldName' -// camelize("Some label that needs to be camelized") -> 'someLabelThatNeedsToBeCamelized' -// camelize("some-javascript-property") -> 'someJavascriptProperty' -// camelize("some-mixed_string with spaces_underscores-and-hyphens") -> 'someMixedStringWithSpacesUnderscoresAndHyphens' +// toCamelCase("some_database_field_name") -> 'someDatabaseFieldName' +// toCamelCase("Some label that needs to be camelized") -> 'someLabelThatNeedsToBeCamelized' +// toCamelCase("some-javascript-property") -> 'someJavascriptProperty' +// toCamelCase("some-mixed_string with spaces_underscores-and-hyphens") -> 'someMixedStringWithSpacesUnderscoresAndHyphens' ``` [⬆ back to top](#table-of-contents) From f280fa631b63e633fcb641c35548c07eaf1bf990 Mon Sep 17 00:00:00 2001 From: David Wu Date: Sat, 16 Dec 2017 20:55:39 +0100 Subject: [PATCH 21/49] Create least-common-multiple-(LCM).md --- snippets/least-common-multiple-(LCM).md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 snippets/least-common-multiple-(LCM).md diff --git a/snippets/least-common-multiple-(LCM).md b/snippets/least-common-multiple-(LCM).md new file mode 100644 index 000000000..1696114f2 --- /dev/null +++ b/snippets/least-common-multiple-(LCM).md @@ -0,0 +1,11 @@ +### Least common multiple (LCM) + +Use this lcm formula `lcm(a,b)=|a*b|/gcd(a,b)` for calculating the least common multiple of two numbers. +Makes use of the [GCD snippet](https://github.com/Chalarangelo/30-seconds-of-code#greatest-common-divisor-gcd). + +```js +const lcm = (x,y) => Math.abs(x*y)/(gcd(x,y)); +const gcd = (x, y) => !y ? x : gcd(y, x % y); +// lcm(10,5) -> 10 +// lcm(12,7) -> 84 +``` From 3f4af69fafc73984fc153cc73afaa75f18162555 Mon Sep 17 00:00:00 2001 From: iamsoorena Date: Sun, 17 Dec 2017 00:55:22 +0330 Subject: [PATCH 22/49] adding intellij related files to gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 9fe5cb489..22010c5cb 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ node_modules/ currentSnippet\.js *.md.temp.js +.idea From 7667f0d975a325b8501233adb3908e209048a422 Mon Sep 17 00:00:00 2001 From: iamsoorena Date: Sun, 17 Dec 2017 01:05:53 +0330 Subject: [PATCH 23/49] removing duplicate code and converting it to one line using `shortHex.startsWith('#') ? 1 : 0` making function more terse removing unnecessary empty strings. --- snippets/3-digit-hexcode-to-6-digit-hexcode.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/snippets/3-digit-hexcode-to-6-digit-hexcode.md b/snippets/3-digit-hexcode-to-6-digit-hexcode.md index a138b34bb..17a4561db 100644 --- a/snippets/3-digit-hexcode-to-6-digit-hexcode.md +++ b/snippets/3-digit-hexcode-to-6-digit-hexcode.md @@ -4,8 +4,7 @@ Use `Array.map()`, `split()` and `Array.join()` to join the mapped array for con ```js const convertHex = shortHex => - shortHex[0] == '#' ? ('#' + shortHex.slice(1).split('').map(x => x+x).join('')) : - ('#' + shortHex.split('').map(x => x+x).join('')); + '#' + shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split().map(x => x+x).join() // convertHex('#03f') -> '#0033ff' // convertHex('05a') -> '#0055aa' ``` From 22ab1e25709b28ce833be1ee2e8acd965372a5e5 Mon Sep 17 00:00:00 2001 From: iamsoorena Date: Sun, 17 Dec 2017 01:08:34 +0330 Subject: [PATCH 24/49] updating description to address slice() part functionality --- snippets/3-digit-hexcode-to-6-digit-hexcode.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/snippets/3-digit-hexcode-to-6-digit-hexcode.md b/snippets/3-digit-hexcode-to-6-digit-hexcode.md index 17a4561db..3c1c87261 100644 --- a/snippets/3-digit-hexcode-to-6-digit-hexcode.md +++ b/snippets/3-digit-hexcode-to-6-digit-hexcode.md @@ -1,7 +1,7 @@ ### 3-digit hexcode to 6-digit hexcode -Use `Array.map()`, `split()` and `Array.join()` to join the mapped array for converting a three-digit RGB notated hexadecimal colorcode to the six-digit form. - +Use `Array.map()`, `split()` and `Array.join()` to join the mapped array for converting a three-digit RGB notated hexadecimal color-code to the six-digit form. +`Array.slice()` is used to remove `#` from string start since it's added once. ```js const convertHex = shortHex => '#' + shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split().map(x => x+x).join() From 51c9f9d4ad7a30694402e44a0f5fa9b11f172c40 Mon Sep 17 00:00:00 2001 From: iamsoorena Date: Sun, 17 Dec 2017 01:25:03 +0330 Subject: [PATCH 25/49] updating function to use spread operator to make it more ES6ish --- snippets/number-to-array-of-digits.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snippets/number-to-array-of-digits.md b/snippets/number-to-array-of-digits.md index f00a62b75..3e14c2c36 100644 --- a/snippets/number-to-array-of-digits.md +++ b/snippets/number-to-array-of-digits.md @@ -4,6 +4,6 @@ Convert the number to a string, use `split()` to convert build an array. Use `Array.map()` and `parseInt()` to transform each value to an integer. ```js -const digitize = n => (''+n).split('').map(i => parseInt(i)); +const digitize = n => [...''+n].map(i => parseInt(i)); // digitize(2334) -> [2, 3, 3, 4] ``` From 81a8d1d6b96ba3265683d17d633359fa08ad2520 Mon Sep 17 00:00:00 2001 From: iamsoorena Date: Sun, 17 Dec 2017 01:27:01 +0330 Subject: [PATCH 26/49] replacing explanation regarding spread operator --- snippets/number-to-array-of-digits.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snippets/number-to-array-of-digits.md b/snippets/number-to-array-of-digits.md index 3e14c2c36..3d8a3c0e0 100644 --- a/snippets/number-to-array-of-digits.md +++ b/snippets/number-to-array-of-digits.md @@ -1,6 +1,6 @@ ### Number to array of digits -Convert the number to a string, use `split()` to convert build an array. +Convert the number to a string, using spread operators in ES6(`[...string]`) build an array. Use `Array.map()` and `parseInt()` to transform each value to an integer. ```js From d8656641025f0bd42e4872348dd4791378213d11 Mon Sep 17 00:00:00 2001 From: iamsoorena Date: Sun, 17 Dec 2017 02:15:50 +0330 Subject: [PATCH 27/49] there is no need to make another array to return the last element. the previous implementation was far more slower that simply returning the last index. --- snippets/last-of-list.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/snippets/last-of-list.md b/snippets/last-of-list.md index d27b0b35e..b4729b152 100644 --- a/snippets/last-of-list.md +++ b/snippets/last-of-list.md @@ -1,8 +1,8 @@ ### Last of list -Use `arr.slice(-1)[0]` to get the last element of the given array. +Use `arr.length - 1` to compute index of the last element of the given array and returning it. ```js -const last = arr => arr.slice(-1)[0]; +const last = arr => arr[arr.length - 1]; // last([1,2,3]) -> 3 ``` From 73f37c53c79b76aed3f50119dc694e629879d4e3 Mon Sep 17 00:00:00 2001 From: King Date: Sat, 16 Dec 2017 23:02:33 -0500 Subject: [PATCH 28/49] add pull snippet --- snippets/pull.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 snippets/pull.md diff --git a/snippets/pull.md b/snippets/pull.md new file mode 100644 index 000000000..2507270be --- /dev/null +++ b/snippets/pull.md @@ -0,0 +1,21 @@ +### Pull + +Use `Array.filter()` 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. +Use `Array.push()` to re-populate the original array to equal the pulled values + +```js +const pull = (arr, ...args) => { + let pulled = arr.filter((v, i) => args.indexOf(v) === -1); + arr.length = 0; + pulled.forEach(v => arr.push(v)); +} + +// let myArray = ['a', 'b', 'c', 'a', 'b', 'c']; +// pull(myArray, 'a', 'c'); +// console.log(myArray) -> [ 'b', 'b' ] + +// let test = ['4', '1', '1', '5', '4', '2']; +// pull(test, '4', '1'); +// console.log(myArray) -> [ '5', '2' ] +``` From a60509c005b277d320e24b8f16eebe68e0e28499 Mon Sep 17 00:00:00 2001 From: King Date: Sat, 16 Dec 2017 23:05:18 -0500 Subject: [PATCH 29/49] ran npm run tagger & add array tag to DB --- tag_database | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tag_database b/tag_database index 6cce617ea..07e07435a 100644 --- a/tag_database +++ b/tag_database @@ -56,7 +56,7 @@ is-function:utility is-number:utility is-string:utility is-symbol:utility -JSON-to-date:date +json-to-date: last-of-list:array log-function-name:function measure-time-taken-by-function:utility @@ -71,6 +71,7 @@ pick:array pipe-functions:function powerset:math promisify:function +pull:array random-integer-in-range:math random-number-in-range:math read-file-as-array-of-lines:node @@ -98,4 +99,4 @@ URL-parameters:utility UUID-generator:utility validate-email:utility validate-number:utility -write-JSON-to-file:node +write-json-to-file: From 5dac2f2bbc1da672d949d10cb217eee85f33cd8a Mon Sep 17 00:00:00 2001 From: Kutsan Kaplan Date: Sun, 17 Dec 2017 09:14:05 +0300 Subject: [PATCH 30/49] Update Hexcode to RGB function with bitwise version --- snippets/hexcode-to-RGB.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/snippets/hexcode-to-RGB.md b/snippets/hexcode-to-RGB.md index 852a25ff8..2bb33480f 100644 --- a/snippets/hexcode-to-RGB.md +++ b/snippets/hexcode-to-RGB.md @@ -1,8 +1,11 @@ ### Hexcode to RGB -Use `Array.slice()`, `Array.map()` and `match()` to convert a hexadecimal colorcode (prefixed with `#`) to a string with the RGB values. +Use bitwise right-shift operator and mask bits with `&` (and) operator to convert a hexadecimal color code (prefixed with `#`) to a string with the RGB values. ```js -const hexToRgb = hex => `rgb(${hex.slice(1).match(/.{2}/g).map(x => parseInt(x, 16)).join()})` -// hexToRgb('#27ae60') -> 'rgb(39,174,96)' +const hexToRgb = hex => { + const h = parseInt(hex.slice(1), 16); + return `rgb(${h >> 16}, ${(h & 0x00ff00) >> 8}, ${h & 0x0000ff})`; +} +// hexToRgb('#27ae60') -> 'rgb(39, 174, 96)' ``` From 137fddef9e9a3ceee3e5a739d47f56e0a6d1a91f Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sun, 17 Dec 2017 11:26:53 +0200 Subject: [PATCH 31/49] Update least-common-multiple-(LCM).md --- snippets/least-common-multiple-(LCM).md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/snippets/least-common-multiple-(LCM).md b/snippets/least-common-multiple-(LCM).md index 1696114f2..4f3fc2822 100644 --- a/snippets/least-common-multiple-(LCM).md +++ b/snippets/least-common-multiple-(LCM).md @@ -1,11 +1,12 @@ ### Least common multiple (LCM) -Use this lcm formula `lcm(a,b)=|a*b|/gcd(a,b)` for calculating the least common multiple of two numbers. -Makes use of the [GCD snippet](https://github.com/Chalarangelo/30-seconds-of-code#greatest-common-divisor-gcd). +Use the greatest common divisor (GCD) formula and `Math.abs()` to determine the least common multiple. +The GCD formula uses recursion. ```js -const lcm = (x,y) => Math.abs(x*y)/(gcd(x,y)); -const gcd = (x, y) => !y ? x : gcd(y, x % y); -// lcm(10,5) -> 10 +const lcm = (x,y) => { + const gcd = (x, y) => !y ? x : gcd(y, x % y); + return Math.abs(x*y)/(gcd(x,y)); +}; // lcm(12,7) -> 84 ``` From e1dbf3d20e8c8e987a323c52399c85da61e1c817 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sun, 17 Dec 2017 11:46:41 +0200 Subject: [PATCH 32/49] Update and rename pull.md to array-pull-(mutates-array).md --- .../{pull.md => array-pull-(mutates-array).md} | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) rename snippets/{pull.md => array-pull-(mutates-array).md} (62%) diff --git a/snippets/pull.md b/snippets/array-pull-(mutates-array).md similarity index 62% rename from snippets/pull.md rename to snippets/array-pull-(mutates-array).md index 2507270be..9b91c2c17 100644 --- a/snippets/pull.md +++ b/snippets/array-pull-(mutates-array).md @@ -1,4 +1,4 @@ -### Pull +### Array pull (mutates array) Use `Array.filter()` 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. @@ -6,16 +6,10 @@ Use `Array.push()` to re-populate the original array to equal the pulled values ```js const pull = (arr, ...args) => { - let pulled = arr.filter((v, i) => args.indexOf(v) === -1); - arr.length = 0; - pulled.forEach(v => arr.push(v)); -} - + let pulled = arr.filter((v, i) => args.includes(v)); + arr.length = 0; pulled.forEach(v => arr.push(v)); +}; // let myArray = ['a', 'b', 'c', 'a', 'b', 'c']; // pull(myArray, 'a', 'c'); // console.log(myArray) -> [ 'b', 'b' ] - -// let test = ['4', '1', '1', '5', '4', '2']; -// pull(test, '4', '1'); -// console.log(myArray) -> [ '5', '2' ] ``` From 98190c129b795a4681765c0a2408fabff6d04bd4 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sun, 17 Dec 2017 11:47:17 +0200 Subject: [PATCH 33/49] Update array-pull-(mutates-array).md --- snippets/array-pull-(mutates-array).md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/snippets/array-pull-(mutates-array).md b/snippets/array-pull-(mutates-array).md index 9b91c2c17..3a58225ca 100644 --- a/snippets/array-pull-(mutates-array).md +++ b/snippets/array-pull-(mutates-array).md @@ -1,8 +1,7 @@ ### Array pull (mutates array) -Use `Array.filter()` 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. -Use `Array.push()` to re-populate the original array to equal the pulled values +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. ```js const pull = (arr, ...args) => { From 80cd011cd029a26d27355a51ced78c23fbabae58 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sun, 17 Dec 2017 11:52:35 +0200 Subject: [PATCH 34/49] Tag, lint, build --- README.md | 50 +++++++++++++++++++++++++++++------ snippets/compose-functions.md | 2 +- tag_database | 7 ++--- 3 files changed, 47 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index bb968c164..dffb4b4e9 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ ### Array * [Array difference](#array-difference) * [Array intersection](#array-intersection) +* [Array pull (mutates array)](#array-pull-mutates-array) * [Array remove](#array-remove) * [Array sample](#array-sample) * [Array symmetric difference](#array-symmetric-difference) @@ -79,6 +80,7 @@ * [Fibonacci array generator](#fibonacci-array-generator) * [Greatest common divisor (GCD)](#greatest-common-divisor-gcd) * [Hamming distance](#hamming-distance) +* [Least common multiple (LCM)](#least-common-multiple-lcm) * [Percentile](#percentile) * [Powerset](#powerset) * [Random integer in range](#random-integer-in-range) @@ -154,6 +156,23 @@ const intersection = (a, b) => { const s = new Set(b); return a.filter(x => s.ha [⬆ back to top](#table-of-contents) +### Array pull (mutates array) + +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. + +```js +const pull = (arr, ...args) => { + let pulled = arr.filter((v, i) => args.includes(v)); + arr.length = 0; pulled.forEach(v => arr.push(v)); +}; +// let myArray = ['a', 'b', 'c', 'a', 'b', 'c']; +// pull(myArray, 'a', 'c'); +// console.log(myArray) -> [ 'b', 'b' ] +``` + +[⬆ back to top](#table-of-contents) + ### Array remove Use `Array.filter()` to find array elements that return truthy values and `Array.reduce()` to remove elements using `Array.splice()`. @@ -450,10 +469,10 @@ const initializeArray = (n, value = 0) => Array(n).fill(value); ### Last of list -Use `arr.slice(-1)[0]` to get the last element of the given array. +Use `arr.length - 1` to compute index of the last element of the given array and returning it. ```js -const last = arr => arr.slice(-1)[0]; +const last = arr => arr[arr.length - 1]; // last([1,2,3]) -> 3 ``` @@ -742,6 +761,7 @@ const multiplyAndAdd5 = compose(add5, multiply) multiplyAndAdd5(5, 2) -> 15 */ ``` + [⬆ back to top](#table-of-contents) ### Curry @@ -941,6 +961,21 @@ const hammingDistance = (num1, num2) => [⬆ back to top](#table-of-contents) +### Least common multiple (LCM) + +Use the greatest common divisor (GCD) formula and `Math.abs()` to determine the least common multiple. +The GCD formula uses recursion. + +```js +const lcm = (x,y) => { + const gcd = (x, y) => !y ? x : gcd(y, x % y); + return Math.abs(x*y)/(gcd(x,y)); +}; +// lcm(12,7) -> 84 +``` + +[⬆ back to top](#table-of-contents) + ### Percentile Use `Array.reduce()` to calculate how many numbers are below the value and how many are the same value and @@ -1266,12 +1301,11 @@ const truncate = (str, num) => ### 3-digit hexcode to 6-digit hexcode -Use `Array.map()`, `split()` and `Array.join()` to join the mapped array for converting a three-digit RGB notated hexadecimal colorcode to the six-digit form. - +Use `Array.map()`, `split()` and `Array.join()` to join the mapped array for converting a three-digit RGB notated hexadecimal color-code to the six-digit form. +`Array.slice()` is used to remove `#` from string start since it's added once. ```js const convertHex = shortHex => - shortHex[0] == '#' ? ('#' + shortHex.slice(1).split('').map(x => x+x).join('')) : - ('#' + shortHex.split('').map(x => x+x).join('')); + '#' + shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split().map(x => x+x).join() // convertHex('#03f') -> '#0033ff' // convertHex('05a') -> '#0055aa' ``` @@ -1403,11 +1437,11 @@ const timeTaken = callback => { ### Number to array of digits -Convert the number to a string, use `split()` to convert build an array. +Convert the number to a string, using spread operators in ES6(`[...string]`) build an array. Use `Array.map()` and `parseInt()` to transform each value to an integer. ```js -const digitize = n => (''+n).split('').map(i => parseInt(i)); +const digitize = n => [...''+n].map(i => parseInt(i)); // digitize(2334) -> [2, 3, 3, 4] ``` diff --git a/snippets/compose-functions.md b/snippets/compose-functions.md index d61c9f3b6..4c7248930 100644 --- a/snippets/compose-functions.md +++ b/snippets/compose-functions.md @@ -11,4 +11,4 @@ const multiply = (x, y) => x * y const multiplyAndAdd5 = compose(add5, multiply) multiplyAndAdd5(5, 2) -> 15 */ -``` \ No newline at end of file +``` diff --git a/tag_database b/tag_database index 07e07435a..ef28264d8 100644 --- a/tag_database +++ b/tag_database @@ -2,6 +2,7 @@ anagrams-of-string-(with-duplicates):string array-difference:array array-intersection:array +array-pull-(mutates-array):array array-remove:array array-sample:array array-symmetric-difference:array @@ -56,8 +57,9 @@ is-function:utility is-number:utility is-string:utility is-symbol:utility -json-to-date: +JSON-to-date:date last-of-list:array +least-common-multiple-(LCM):math log-function-name:function measure-time-taken-by-function:utility median-of-array-of-numbers:array @@ -71,7 +73,6 @@ pick:array pipe-functions:function powerset:math promisify:function -pull:array random-integer-in-range:math random-number-in-range:math read-file-as-array-of-lines:node @@ -99,4 +100,4 @@ URL-parameters:utility UUID-generator:utility validate-email:utility validate-number:utility -write-json-to-file: +write-JSON-to-file:node From 8b0be61b2cc0cf760dbaa3aeb3dd9d13fcf2f60f Mon Sep 17 00:00:00 2001 From: Avraam Mavridis Date: Sun, 17 Dec 2017 10:59:28 +0100 Subject: [PATCH 35/49] Use Boolean for compact --- snippets/compact.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snippets/compact.md b/snippets/compact.md index 607634b4a..121d79bae 100644 --- a/snippets/compact.md +++ b/snippets/compact.md @@ -3,6 +3,6 @@ Use `Array.filter()` to filter out falsey values (`false`, `null`, `0`, `""`, `undefined`, and `NaN`). ```js -const compact = (arr) => arr.filter(v => v); +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 c5e63542e63a4748a64c1827490e68c5de9b477a Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sun, 17 Dec 2017 12:18:09 +0200 Subject: [PATCH 36/49] Remove fill array Resolves #203 --- README.md | 25 +++++++------------------ snippets/fill-array.md | 10 ---------- tag_database | 1 - 3 files changed, 7 insertions(+), 29 deletions(-) delete mode 100644 snippets/fill-array.md diff --git a/README.md b/README.md index dffb4b4e9..55de97ea4 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,6 @@ * [Count occurrences of a value in array](#count-occurrences-of-a-value-in-array) * [Deep flatten array](#deep-flatten-array) * [Drop elements in array](#drop-elements-in-array) -* [Fill array](#fill-array) * [Filter out non unique values in an array](#filter-out-non-unique-values-in-an-array) * [Flatten array up to depth](#flatten-array-up-to-depth) * [Flatten array](#flatten-array) @@ -287,7 +286,7 @@ const chunk = (arr, size) => Use `Array.filter()` to filter out falsey values (`false`, `null`, `0`, `""`, `undefined`, and `NaN`). ```js -const compact = (arr) => arr.filter(v => v); +const compact = (arr) => arr.filter(Boolean); // compact([0, 1, false, 2, '', 3, 'a', 'e'*23, NaN, 's', 34]) -> [ 1, 2, 3, 'a', 's', 34 ] ``` @@ -332,19 +331,6 @@ const dropElements = (arr, func) => { [⬆ back to top](#table-of-contents) -### Fill array - -Use `Array.map()` to map values between `start` (inclusive) and `end` (exclusive) to `value`. -Omit `start` to start at the first element and/or `end` to finish at the last. - -```js -const fillArray = (arr, value, start = 0, end = arr.length) => - arr.map((v, i) => i >= start && i < end ? value : v); -// fillArray([1,2,3,4],'8',1,3) -> [1,'8','8',4] -``` - -[⬆ back to top](#table-of-contents) - ### Filter out non-unique values in an array Use `Array.filter()` for an array containing only the unique values. @@ -1337,11 +1323,14 @@ const getType = v => ### Hexcode to RGB -Use `Array.slice()`, `Array.map()` and `match()` to convert a hexadecimal colorcode (prefixed with `#`) to a string with the RGB values. +Use bitwise right-shift operator and mask bits with `&` (and) operator to convert a hexadecimal color code (prefixed with `#`) to a string with the RGB values. ```js -const hexToRgb = hex => `rgb(${hex.slice(1).match(/.{2}/g).map(x => parseInt(x, 16)).join()})` -// hexToRgb('#27ae60') -> 'rgb(39,174,96)' +const hexToRgb = hex => { + const h = parseInt(hex.slice(1), 16); + return `rgb(${h >> 16}, ${(h & 0x00ff00) >> 8}, ${h & 0x0000ff})`; +} +// hexToRgb('#27ae60') -> 'rgb(39, 174, 96)' ``` [⬆ back to top](#table-of-contents) diff --git a/snippets/fill-array.md b/snippets/fill-array.md deleted file mode 100644 index a5da15483..000000000 --- a/snippets/fill-array.md +++ /dev/null @@ -1,10 +0,0 @@ -### Fill array - -Use `Array.map()` to map values between `start` (inclusive) and `end` (exclusive) to `value`. -Omit `start` to start at the first element and/or `end` to finish at the last. - -```js -const fillArray = (arr, value, start = 0, end = arr.length) => - arr.map((v, i) => i >= start && i < end ? value : v); -// fillArray([1,2,3,4],'8',1,3) -> [1,'8','8',4] -``` diff --git a/tag_database b/tag_database index ef28264d8..4abb2563d 100644 --- a/tag_database +++ b/tag_database @@ -34,7 +34,6 @@ escape-regular-expression:utility even-or-odd-number:math factorial:math fibonacci-array-generator:math -fill-array:array filter-out-non-unique-values-in-an-array:array flatten-array-up-to-depth:array flatten-array:array From 622b4286c6253331aa76e4c81dfd8463c707594a Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sun, 17 Dec 2017 12:48:07 +0200 Subject: [PATCH 37/49] Merge #113 --- README.md | 14 ++++++++++++++ snippets/convert-to-english-date.md | 10 ++++++++++ tag_database | 1 + 3 files changed, 25 insertions(+) create mode 100644 snippets/convert-to-english-date.md diff --git a/README.md b/README.md index 55de97ea4..e2bea8313 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,7 @@ * [Scroll to top](#scroll-to-top) ### Date +* [Convert to english date](#convert-to-english-date) * [Get days difference between dates](#get-days-difference-between-dates) * [JSON to date](#json-to-date) @@ -690,6 +691,19 @@ const scrollToTop = _ => { [⬆ back to top](#table-of-contents) ## Date +### Convert to English date + +Use `Date.toISOString()`, `split('T')` and `replace()` to convert a date from American format to English format. +Throws an error if the passed time cannot be converted to a date. + +```js +const toEnglishDate = (time) => + {try{return new Date(time).toISOString().split('T')[0].replace(/-/g, '/')}catch(e){return}}; +// toEnglishDate('09/21/2010') -> '21/09/2010' +``` + +[⬆ back to top](#table-of-contents) + ### Get days difference between dates Calculate the difference (in days) between to `Date` objects. diff --git a/snippets/convert-to-english-date.md b/snippets/convert-to-english-date.md new file mode 100644 index 000000000..01a93cdf5 --- /dev/null +++ b/snippets/convert-to-english-date.md @@ -0,0 +1,10 @@ +### Convert to English date + +Use `Date.toISOString()`, `split('T')` and `replace()` to convert a date from American format to English format. +Throws an error if the passed time cannot be converted to a date. + +```js +const toEnglishDate = (time) => + {try{return new Date(time).toISOString().split('T')[0].replace(/-/g, '/')}catch(e){return}}; +// toEnglishDate('09/21/2010') -> '21/09/2010' +``` diff --git a/tag_database b/tag_database index 4abb2563d..56a50f864 100644 --- a/tag_database +++ b/tag_database @@ -22,6 +22,7 @@ compact:array compose-functions:function convert-string-from-camelcase:string convert-string-to-camelcase:string +convert-to-english-date:date count-occurrences-of-a-value-in-array:array current-URL:browser curry:function From a68d34eaafd638a6a4cb073c1f0cf6394cfac5ee Mon Sep 17 00:00:00 2001 From: Kladdkaka Date: Sun, 17 Dec 2017 11:54:10 +0100 Subject: [PATCH 38/49] Update CONTRIBUTING.md --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 37b9cc767..b8307cda9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -55,7 +55,7 @@ Here's what you can do to help: - `i` for indexes. - `func` for function arguments. - `nums` for arrays of numbers. -- Use `_` if your function takes no arguments or if an argument inside some function (e.g. `Array.reduce()`) is not used anywhere in your code. +- Use `()` if your function takes no arguments or if an argument inside some function (e.g. `Array.reduce()`) is not used anywhere in your code. - Specify default parameters for arguments, if necessary. It is preferred to put default parameters last unless you have pretty good reason not to. - If your snippet's function takes variadic arguments, use `..args` (although in certain cases, it might be needed to use a different name). - If your snippet function's body is a single statement, omit the `return` keyword and use an expression instead. From e20190c5345c7483ae38bc32bd20542dafd50ea9 Mon Sep 17 00:00:00 2001 From: Kladdkaka Date: Sun, 17 Dec 2017 11:54:53 +0100 Subject: [PATCH 39/49] changing _ to () --- snippets/bottom-visible.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snippets/bottom-visible.md b/snippets/bottom-visible.md index b94ac773a..797b0eb00 100644 --- a/snippets/bottom-visible.md +++ b/snippets/bottom-visible.md @@ -3,7 +3,7 @@ Use `scrollY`, `scrollHeight` and `clientHeight` to determine if the bottom of the page is visible. ```js -const bottomVisible = _ => +const bottomVisible = () => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight || document.documentElement.clientHeight; // bottomVisible() -> true ``` From 5cf046de09f8ff68b76b025e70ed2090c33d9d35 Mon Sep 17 00:00:00 2001 From: Kladdkaka Date: Sun, 17 Dec 2017 11:55:13 +0100 Subject: [PATCH 40/49] changing _ to () --- snippets/current-URL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snippets/current-URL.md b/snippets/current-URL.md index 200cf150b..3a549d219 100644 --- a/snippets/current-URL.md +++ b/snippets/current-URL.md @@ -3,6 +3,6 @@ Use `window.location.href` to get current URL. ```js -const currentUrl = _ => window.location.href; +const currentUrl = () => window.location.href; // currentUrl() -> 'https://google.com' ``` From ffabf8d94cba2146189c6a542c677eb171ae7f29 Mon Sep 17 00:00:00 2001 From: Kladdkaka Date: Sun, 17 Dec 2017 11:55:41 +0100 Subject: [PATCH 41/49] changing _ to () --- snippets/scroll-to-top.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snippets/scroll-to-top.md b/snippets/scroll-to-top.md index 6c82190a4..19064a5d5 100644 --- a/snippets/scroll-to-top.md +++ b/snippets/scroll-to-top.md @@ -4,7 +4,7 @@ Get distance from top using `document.documentElement.scrollTop` or `document.bo Scroll by a fraction of the distance from top. Use `window.requestAnimationFrame()` to animate the scrolling. ```js -const scrollToTop = _ => { +const scrollToTop = () => { const c = document.documentElement.scrollTop || document.body.scrollTop; if (c > 0) { window.requestAnimationFrame(scrollToTop); From 4a1989764b3b58e001c26a333b0dabf58e9c8b3f Mon Sep 17 00:00:00 2001 From: Kladdkaka Date: Sun, 17 Dec 2017 11:56:01 +0100 Subject: [PATCH 42/49] Update UUID-generator.md --- snippets/UUID-generator.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snippets/UUID-generator.md b/snippets/UUID-generator.md index 01d4e27ac..342fce12b 100644 --- a/snippets/UUID-generator.md +++ b/snippets/UUID-generator.md @@ -3,7 +3,7 @@ Use `crypto` API to generate a UUID, compliant with [RFC4122](https://www.ietf.org/rfc/rfc4122.txt) version 4. ```js -const uuid = _ => +const uuid = () => ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16) ); From ffb230ebad8449c206365492c71d9cf1be903962 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sun, 17 Dec 2017 13:00:35 +0200 Subject: [PATCH 43/49] Update CONTRIBUTING.md --- CONTRIBUTING.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b8307cda9..15aab603c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -55,7 +55,8 @@ Here's what you can do to help: - `i` for indexes. - `func` for function arguments. - `nums` for arrays of numbers. -- Use `()` if your function takes no arguments or if an argument inside some function (e.g. `Array.reduce()`) is not used anywhere in your code. +- Use `()` if your function takes no arguments. +- Use `_` if an argument inside some function (e.g. `Array.reduce()`) is not used anywhere in your code. - Specify default parameters for arguments, if necessary. It is preferred to put default parameters last unless you have pretty good reason not to. - If your snippet's function takes variadic arguments, use `..args` (although in certain cases, it might be needed to use a different name). - If your snippet function's body is a single statement, omit the `return` keyword and use an expression instead. From 91a2d15b485923cd1ee3b05ffd5f63e0bdcc0e18 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sun, 17 Dec 2017 13:01:31 +0200 Subject: [PATCH 44/49] Build --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index e2bea8313..9bff6ff45 100644 --- a/README.md +++ b/README.md @@ -605,7 +605,7 @@ const unique = arr => [...new Set(arr)]; Use `scrollY`, `scrollHeight` and `clientHeight` to determine if the bottom of the page is visible. ```js -const bottomVisible = _ => +const bottomVisible = () => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight || document.documentElement.clientHeight; // bottomVisible() -> true ``` @@ -617,7 +617,7 @@ const bottomVisible = _ => Use `window.location.href` to get current URL. ```js -const currentUrl = _ => window.location.href; +const currentUrl = () => window.location.href; // currentUrl() -> 'https://google.com' ``` @@ -678,7 +678,7 @@ Get distance from top using `document.documentElement.scrollTop` or `document.bo Scroll by a fraction of the distance from top. Use `window.requestAnimationFrame()` to animate the scrolling. ```js -const scrollToTop = _ => { +const scrollToTop = () => { const c = document.documentElement.scrollTop || document.body.scrollTop; if (c > 0) { window.requestAnimationFrame(scrollToTop); @@ -1499,7 +1499,7 @@ const getUrlParameters = url => Use `crypto` API to generate a UUID, compliant with [RFC4122](https://www.ietf.org/rfc/rfc4122.txt) version 4. ```js -const uuid = _ => +const uuid = () => ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16) ); From f361a313ae17d729bbf95d3c50d0559c22d18855 Mon Sep 17 00:00:00 2001 From: Vivek Date: Sun, 17 Dec 2017 16:34:58 +0530 Subject: [PATCH 45/49] Updated ReadMe.md changed `indow.speechSynthesis.getVoices()` to `window.speechSynthesis.getVoices()` in Speech synthesis (experimental) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9bff6ff45..d4952bec4 100644 --- a/README.md +++ b/README.md @@ -1058,7 +1058,7 @@ const standardDeviation = (arr, usePopulation = false) => { ### Speech synthesis (experimental) -Use `SpeechSynthesisUtterance.voice` and `indow.speechSynthesis.getVoices()` to convert a message to speech. +Use `SpeechSynthesisUtterance.voice` and `window.speechSynthesis.getVoices()` to convert a message to speech. Use `window.speechSynthesis.speak()` to play the message. Learn more about the [SpeechSynthesisUtterance interface of the Web Speech API](https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesisUtterance). From daf0c38d6e76466658eb302577851c424a9c07b3 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sun, 17 Dec 2017 13:12:10 +0200 Subject: [PATCH 46/49] Fix typo --- snippets/speech-synthesis-(experimental).md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snippets/speech-synthesis-(experimental).md b/snippets/speech-synthesis-(experimental).md index c9e6a288c..2a5cb1d20 100644 --- a/snippets/speech-synthesis-(experimental).md +++ b/snippets/speech-synthesis-(experimental).md @@ -1,6 +1,6 @@ ### Speech synthesis (experimental) -Use `SpeechSynthesisUtterance.voice` and `indow.speechSynthesis.getVoices()` to convert a message to speech. +Use `SpeechSynthesisUtterance.voice` and `window.speechSynthesis.getVoices()` to convert a message to speech. Use `window.speechSynthesis.speak()` to play the message. Learn more about the [SpeechSynthesisUtterance interface of the Web Speech API](https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesisUtterance). From 3cacd6defc1065661a1c6b4502b4d3a082fc8299 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sun, 17 Dec 2017 13:16:27 +0200 Subject: [PATCH 47/49] Create CODE_OF_CONDUCT.md --- CODE_OF_CONDUCT.md | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 CODE_OF_CONDUCT.md diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 000000000..df46a145a --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,46 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at chalarangelo@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ From 0652351e4827b0cf42fca741b76b3517e74a5ac4 Mon Sep 17 00:00:00 2001 From: Sergey Chichulin Date: Sun, 17 Dec 2017 14:33:52 +0200 Subject: [PATCH 48/49] fix array-pull to pull out values correctly --- snippets/array-pull-(mutates-array).md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snippets/array-pull-(mutates-array).md b/snippets/array-pull-(mutates-array).md index 3a58225ca..d20e21c5e 100644 --- a/snippets/array-pull-(mutates-array).md +++ b/snippets/array-pull-(mutates-array).md @@ -5,7 +5,7 @@ Use `Array.length = 0` to mutate the passed in array by resetting it's length to ```js const pull = (arr, ...args) => { - let pulled = arr.filter((v, i) => args.includes(v)); + let pulled = arr.filter((v, i) => !args.includes(v)); arr.length = 0; pulled.forEach(v => arr.push(v)); }; // let myArray = ['a', 'b', 'c', 'a', 'b', 'c']; From 01ec8afce7500ca034b02a0c5c99c37458cc69f7 Mon Sep 17 00:00:00 2001 From: Sergey Chichulin Date: Sun, 17 Dec 2017 14:53:24 +0200 Subject: [PATCH 49/49] update Array pull in README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d4952bec4..c9dd3b8b4 100644 --- a/README.md +++ b/README.md @@ -163,7 +163,7 @@ Use `Array.length = 0` to mutate the passed in array by resetting it's length to ```js const pull = (arr, ...args) => { - let pulled = arr.filter((v, i) => args.includes(v)); + let pulled = arr.filter((v, i) => !args.includes(v)); arr.length = 0; pulled.forEach(v => arr.push(v)); }; // let myArray = ['a', 'b', 'c', 'a', 'b', 'c'];