From e5949c90a53bc33ef8c94fac600571329eaab3c1 Mon Sep 17 00:00:00 2001 From: sabareesh Date: Thu, 14 Dec 2017 16:51:34 +0530 Subject: [PATCH 01/24] lodash remove duplicated --- README.md | 14 ++++++++++++++ snippets/remove.md | 12 ++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 snippets/remove.md diff --git a/README.md b/README.md index 77a5233e9..eacb3932a 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,7 @@ * [Random number in range](#random-number-in-range) * [Randomize order of array](#randomize-order-of-array) * [Redirect to url](#redirect-to-url) +* [Remove](#remove) * [Reverse a string](#reverse-a-string) * [RGB to hexadecimal](#rgb-to-hexadecimal) * [Run promises in series](#run-promises-in-series) @@ -610,6 +611,19 @@ const redirect = (url, asLink = true) => // redirect('https://google.com') ``` +### Remove + +Remove elements from `arr` that are returns truthy. Use `Array.filter()` to finding the matching elements and `Array.reduce()` to remove elements using `Array.splice()`.The `func` is invoked with three arguments: (value, index, array). + +```js +const remove = (arr, func) => + arr.filter(func).reduce((acc, val) => { + arr.splice(arr.indexOf(val), 1) + return acc.concat(val); + }, []) +//remove([1, 2, 3, 4], n => n % 2 == 0) -> [2, 4] +``` + ### Reverse a string Use array destructuring and `Array.reverse()` to reverse the order of the characters in the string. diff --git a/snippets/remove.md b/snippets/remove.md new file mode 100644 index 000000000..6c8e71d55 --- /dev/null +++ b/snippets/remove.md @@ -0,0 +1,12 @@ +### Remove + +Remove elements from `arr` that are returns truthy. Use `Array.filter()` to finding the matching elements and `Array.reduce()` to remove elements using `Array.splice()`.The `func` is invoked with three arguments: (value, index, array). + +```js +const remove = (arr, func) => + arr.filter(func).reduce((acc, val) => { + arr.splice(arr.indexOf(val), 1) + return acc.concat(val); + }, []) +//remove([1, 2, 3, 4], n => n % 2 == 0) -> [2, 4] +``` From 123ca7943f5ee475ab96de9578eec90d13cf27c1 Mon Sep 17 00:00:00 2001 From: sabareesh Date: Thu, 14 Dec 2017 16:56:32 +0530 Subject: [PATCH 02/24] lodash remove duplicated --- README.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/README.md b/README.md index c8a19046c..12e86b020 100644 --- a/README.md +++ b/README.md @@ -57,13 +57,9 @@ * [Promisify](#promisify) * [Random integer in range](#random-integer-in-range) * [Random number in range](#random-number-in-range) -<<<<<<< HEAD * [Randomize order of array](#randomize-order-of-array) * [Redirect to url](#redirect-to-url) * [Remove](#remove) -======= -* [Redirect to URL](#redirect-to-url) ->>>>>>> 10ae7ad867aaa94d27da81180760d6a0fa84a3a8 * [Reverse a string](#reverse-a-string) * [RGB to hexadecimal](#rgb-to-hexadecimal) * [Run promises in series](#run-promises-in-series) From adbba8810a291e9c20656a4cb5cce4534f599e49 Mon Sep 17 00:00:00 2001 From: iamsoorena Date: Thu, 14 Dec 2017 18:00:15 +0330 Subject: [PATCH 03/24] add json to file function --- snippets/write-json-to-file.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 snippets/write-json-to-file.md diff --git a/snippets/write-json-to-file.md b/snippets/write-json-to-file.md new file mode 100644 index 000000000..6a0ae21a0 --- /dev/null +++ b/snippets/write-json-to-file.md @@ -0,0 +1,9 @@ +### Write a JSON to a file + +Write a `json` object to a `.json` file. +```js +const fs = require('fs') + +const jsonToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 4)) +// jsonToFile({test: "is passed"}, 'testJsonFile') +``` From 99b900853cf82910be517647ecbafc2bc11b8d8b Mon Sep 17 00:00:00 2001 From: iamsoorena Date: Thu, 14 Dec 2017 18:34:05 +0330 Subject: [PATCH 04/24] add a functions that deeply cleans json objects from unwanted keys --- snippets/json-cleaner.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 snippets/json-cleaner.md diff --git a/snippets/json-cleaner.md b/snippets/json-cleaner.md new file mode 100644 index 000000000..46ef745dc --- /dev/null +++ b/snippets/json-cleaner.md @@ -0,0 +1,20 @@ +### Clean Json objects + +Clean your json object from unwanted keys, deeply. +provide set of `keys` to keep and an indicator for `children` if there is any. + +```js +const cleanObj = (obj, keys = [], childIndicator) => { + Object.keys(obj).forEach(key => { + if (key === childIndicator) { + cleanObj(obj[key], keys, childIndicator) + } else if (!keys.includes(key)) { + delete obj[key] + } + }) +} +/* + dirtyObj = { a: 1, b: 2, children: {a: 1, b :2}} + let cleaned = cleanObj(dirtyObj, [a]) // { a: 1, children : { a: 1}} + */ +``` From 30a0d91372e932d5197656d42df8e7ee317a45e1 Mon Sep 17 00:00:00 2001 From: David Wu Date: Fri, 15 Dec 2017 00:48:15 +0100 Subject: [PATCH 05/24] Create hexidecimal-to-RGB.md --- snippets/hexidecimal-to-RGB.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 snippets/hexidecimal-to-RGB.md diff --git a/snippets/hexidecimal-to-RGB.md b/snippets/hexidecimal-to-RGB.md new file mode 100644 index 000000000..73ee1d18d --- /dev/null +++ b/snippets/hexidecimal-to-RGB.md @@ -0,0 +1,14 @@ +### Hexadecimal to RGB + +Converts hexadecimal colorcodes to RGB colorcodes by matching the hexidecimal (two-digit) red, green and blue values and +mapping their decimal equivalents to an array [r, g, b]. Works also with shorthand hex triplets such as "#05F". + +```js +const hexToRgb = hex => + hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i + ,(m, r, g, b) => '#' + r + r + g + g + b + b) + .substring(1).match(/.{2}/g) + .map(x => parseInt(x, 16)) +// hexToRgb('#27ae60') -> '[39, 174, 96]' +// hexToRgb('#aaa') -> '[170, 170, 170]' +``` From a64f389c78c639e23714f3cfaaf3fb856c2eafd0 Mon Sep 17 00:00:00 2001 From: David Wu Date: Fri, 15 Dec 2017 01:00:44 +0100 Subject: [PATCH 06/24] Rename hexidecimal-to-RGB.md to hexadecimal-to-RGB.md --- snippets/{hexidecimal-to-RGB.md => hexadecimal-to-RGB.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename snippets/{hexidecimal-to-RGB.md => hexadecimal-to-RGB.md} (100%) diff --git a/snippets/hexidecimal-to-RGB.md b/snippets/hexadecimal-to-RGB.md similarity index 100% rename from snippets/hexidecimal-to-RGB.md rename to snippets/hexadecimal-to-RGB.md From 4e7085b5ba5fcb7efdc25f2a2531cbb63bf2b117 Mon Sep 17 00:00:00 2001 From: sabareesh Date: Fri, 15 Dec 2017 11:41:51 +0530 Subject: [PATCH 07/24] new arrray remove and concat issue fixed --- README.md | 13 ++++++++++++- snippets/array-concatenation.md | 2 +- snippets/remove.md | 2 ++ 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 12e86b020..35db7870c 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ ## Contents * [Anagrams of string (with duplicates)](#anagrams-of-string-with-duplicates) +* [Array concatenation](#array-concatenation) * [Array difference](#array-difference) * [Array intersection](#array-intersection) * [Array union](#array-union) @@ -57,7 +58,6 @@ * [Promisify](#promisify) * [Random integer in range](#random-integer-in-range) * [Random number in range](#random-number-in-range) -* [Randomize order of array](#randomize-order-of-array) * [Redirect to url](#redirect-to-url) * [Remove](#remove) * [Reverse a string](#reverse-a-string) @@ -97,6 +97,15 @@ const anagrams = str => { // anagrams('abc') -> ['abc','acb','bac','bca','cab','cba'] ``` +### Array concatenation + +Use `Array.concat()` to concatenate and array with any additional arrays and/or values, specified in `args`. + +```js +const ArrayConcat = (arr, ...args) => [].concat(arr, ...args); +// ArrayConcat([1], [1, 2, 3, [4]]) -> [1, 2, 3, [4]] +``` + ### Array difference Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values not contained in `b`. @@ -618,10 +627,12 @@ Remove elements from `arr` that are returns truthy. Use `Array.filter()` to find ```js const remove = (arr, func) => + Array.isArray(arr) ? arr.filter(func).reduce((acc, val) => { arr.splice(arr.indexOf(val), 1) return acc.concat(val); }, []) + : []; //remove([1, 2, 3, 4], n => n % 2 == 0) -> [2, 4] ``` diff --git a/snippets/array-concatenation.md b/snippets/array-concatenation.md index 39d978d6e..f441a0a17 100644 --- a/snippets/array-concatenation.md +++ b/snippets/array-concatenation.md @@ -3,6 +3,6 @@ Use `Array.concat()` to concatenate and array with any additional arrays and/or values, specified in `args`. ```js -const ArrayConcat = (arr, ...args) => arr.concat(...args); +const ArrayConcat = (arr, ...args) => [].concat(arr, ...args); // ArrayConcat([1], [1, 2, 3, [4]]) -> [1, 2, 3, [4]] ``` diff --git a/snippets/remove.md b/snippets/remove.md index 6c8e71d55..0a25e6f00 100644 --- a/snippets/remove.md +++ b/snippets/remove.md @@ -4,9 +4,11 @@ Remove elements from `arr` that are returns truthy. Use `Array.filter()` to find ```js const remove = (arr, func) => + Array.isArray(arr) ? arr.filter(func).reduce((acc, val) => { arr.splice(arr.indexOf(val), 1) return acc.concat(val); }, []) + : []; //remove([1, 2, 3, 4], n => n % 2 == 0) -> [2, 4] ``` From bec3c5afa6d15160675d42145c904eb78132831c Mon Sep 17 00:00:00 2001 From: iamsoorena Date: Fri, 15 Dec 2017 12:56:13 +0330 Subject: [PATCH 08/24] removing unrelated file from "to merge" branch --- snippets/json-cleaner.md | 20 -------------------- 1 file changed, 20 deletions(-) delete mode 100644 snippets/json-cleaner.md diff --git a/snippets/json-cleaner.md b/snippets/json-cleaner.md deleted file mode 100644 index 46ef745dc..000000000 --- a/snippets/json-cleaner.md +++ /dev/null @@ -1,20 +0,0 @@ -### Clean Json objects - -Clean your json object from unwanted keys, deeply. -provide set of `keys` to keep and an indicator for `children` if there is any. - -```js -const cleanObj = (obj, keys = [], childIndicator) => { - Object.keys(obj).forEach(key => { - if (key === childIndicator) { - cleanObj(obj[key], keys, childIndicator) - } else if (!keys.includes(key)) { - delete obj[key] - } - }) -} -/* - dirtyObj = { a: 1, b: 2, children: {a: 1, b :2}} - let cleaned = cleanObj(dirtyObj, [a]) // { a: 1, children : { a: 1}} - */ -``` From 453026fe3b2ccaf246b4bf04f2e58b1db68ba9ca Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Fri, 15 Dec 2017 12:53:09 +0200 Subject: [PATCH 09/24] Tag, lint, build --- README.md | 79 +++++++++++++++++++++-- snippets/array-sample.md | 8 +-- snippets/{without.md => array-without.md} | 9 +-- snippets/array-zip.md | 7 +- snippets/deep-flatten-array.md | 3 +- snippets/pipe.md | 9 ++- snippets/{takeRight.md => take-right.md} | 5 +- tag_database | 6 +- 8 files changed, 94 insertions(+), 32 deletions(-) rename snippets/{without.md => array-without.md} (88%) rename snippets/{takeRight.md => take-right.md} (83%) diff --git a/README.md b/README.md index 7160b9afb..b8412a802 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,10 @@ * [Array concatenation](#array-concatenation) * [Array difference](#array-difference) * [Array intersection](#array-intersection) +* [Array sample](#array-sample) * [Array union](#array-union) +* [Array without](#array-without) +* [Array zip](#array-zip) * [Average of array of numbers](#average-of-array-of-numbers) * [Chunk array](#chunk-array) * [Compact](#compact) @@ -39,6 +42,7 @@ * [Similarity between arrays](#similarity-between-arrays) * [Sum of array of numbers](#sum-of-array-of-numbers) * [Tail of list](#tail-of-list) +* [Take right](#take-right) * [Take](#take) * [Unique values of array](#unique-values-of-array) @@ -149,6 +153,18 @@ const intersection = (a, b) => { const s = new Set(b); return a.filter(x => s.ha [⬆ back to top](#table-of-contents) +### Array sample + +Use `Math.random()` to generate a random number, multiply it with `length` and round it of to the nearest whole number using `Math.floor()`. +This method also works with strings. + +```js +const sample = arr => arr[Math.floor(Math.random() * arr.length)]; +// sample([3, 7, 9, 11]) -> 9 +``` + +[⬆ back to top](#table-of-contents) + ### Array union Create a `Set` with all values of `a` and `b` and convert to an array. @@ -160,6 +176,37 @@ const union = (a, b) => Array.from(new Set([...a, ...b])); [⬆ back to top](#table-of-contents) +### Array without + +Use `Array.filter()` to create an array excluding all given values. + +```js +const without = (arr, ...args) => arr.filter(v => args.indexOf(v) === -1); +// without[2, 1, 2, 3], 1, 2) -> [3] +// without([2, 1, 2, 3, 4, 5, 5, 5, 3, 2, 7, 7], 3, 1, 5, 2) -> [ 4, 7, 7 ] +``` + +[⬆ back to top](#table-of-contents) + +### Array zip + +Use `Math.max.apply()` to get the longest array in the arguments. +Creates an array with that length as return value and use `Array.from()` with a map-function to create an array of grouped elements. +If lengths of the argument-arrays vary, `undefined` is used where no value could be found. + +```js +const zip = (...arrays) => { + const maxLength = Math.max.apply(null, arrays.map(a => a.length)); + return Array.from({length: maxLength}).map((_, i) => { + return Array.from({length: arrays.length}, (_, k) => arrays[k][i]); + }) +} +//zip(['a', 'b'], [1, 2], [true, false]); -> [['a', 1, true], ['b', 2, false]] +//zip(['a'], [1, 2], [true, false]); -> [['a', 1, true], [undefined, 2, false]] +``` + +[⬆ back to top](#table-of-contents) + ### Average of array of numbers Use `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`, divide by the `length` of the array. @@ -180,7 +227,7 @@ If the original array can't be split evenly, the final chunk will contain the re ```js const chunk = (arr, size) => Array.from({length: Math.ceil(arr.length / size)}, (v, i) => arr.slice(i * size, i * size + size)); -// chunk([1,2,3,4,5], 2) -> [[1,2],[3,4],5] +// chunk([1,2,3,4,5], 2) -> [[1,2],[3,4],[5]] ``` [⬆ back to top](#table-of-contents) @@ -210,11 +257,11 @@ const countOccurrences = (arr, value) => arr.reduce((a, v) => v === value ? a + ### Deep flatten array Use recursion. -Use `Array.reduce()` to get all elements that are not arrays, flatten each element that is an array. +Use `Array.concat()` with an empty array (`[]`) and the spread operator (`...`) to flatten an array. +Rrecursively flatten each element that is an array. ```js -const deepFlatten = arr => - arr.reduce((a, v) => a.concat(Array.isArray(v) ? deepFlatten(v) : v), []); +const deepFlatten = arr => [].concat(...arr.map(v => Array.isArray(v) ? deepFlatten(v) : v)); // deepFlatten([1,[2],[[3],4],5]) -> [1,2,3,4,5] ``` @@ -469,6 +516,18 @@ const tail = arr => arr.length > 1 ? arr.slice(1) : arr; [⬆ back to top](#table-of-contents) +### Take right + +Use `Array.slice()` to create a slice of the array with `n` elements taken from the end. + +```js +const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length); +// takeRight([1, 2, 3], 2) -> [ 2, 3 ] +// takeRight([1, 2, 3]) -> [3] +``` + +[⬆ back to top](#table-of-contents) + ### Take Use `Array.slice()` to create a slice of the array with `n` elements taken from the beginning. @@ -633,11 +692,17 @@ const curry = (fn, arity = fn.length, ...args) => ### Pipe -Use `Array.reduce()` to pass value through functions. +Use `Array.reduce()` to perform left-to-right function composition. +The first (leftmost) function can accept one or more arguments; the remaining functions must be unary. ```js -const pipe = (...funcs) => arg => funcs.reduce((acc, func) => func(acc), arg); -// pipe(btoa, x => x.toUpperCase())("Test") -> "VGVZDA==" +const pipe = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); +/* +const add5 = x => x + 5 +const multiply = (x, y) => x * y +const multiplyAndAdd5 = pipe(multiply, add5) +multiplyAndAdd5(5, 2) -> 15 +*/ ``` [⬆ back to top](#table-of-contents) diff --git a/snippets/array-sample.md b/snippets/array-sample.md index d48f13840..9de5c5ae0 100644 --- a/snippets/array-sample.md +++ b/snippets/array-sample.md @@ -1,9 +1,9 @@ ### Array sample -Use `Math.random()` to generate a random number, multiply it with `Array.length` and round it of to the nearest whole number using `Math.floor()`. Works with strings too. +Use `Math.random()` to generate a random number, multiply it with `length` and round it of to the nearest whole number using `Math.floor()`. +This method also works with strings. ```js const sample = arr => arr[Math.floor(Math.random() * arr.length)]; - -// sample([3, 7, 9, 11]) -> 9 -``` \ No newline at end of file +// sample([3, 7, 9, 11]) -> 9 +``` diff --git a/snippets/without.md b/snippets/array-without.md similarity index 88% rename from snippets/without.md rename to snippets/array-without.md index 00876b5c9..dd657fe2a 100644 --- a/snippets/without.md +++ b/snippets/array-without.md @@ -1,12 +1,9 @@ -### Without +### Array without -Use `Array.filter()` to create an array excluding all given values +Use `Array.filter()` to create an array excluding all given values. ```js - -const without = (arr, ...args) => arr.filter(v => args.indexOf(v) === -1) - +const without = (arr, ...args) => arr.filter(v => args.indexOf(v) === -1); // without[2, 1, 2, 3], 1, 2) -> [3] // without([2, 1, 2, 3, 4, 5, 5, 5, 3, 2, 7, 7], 3, 1, 5, 2) -> [ 4, 7, 7 ] - ``` diff --git a/snippets/array-zip.md b/snippets/array-zip.md index 08c40ed68..6c9a2491b 100644 --- a/snippets/array-zip.md +++ b/snippets/array-zip.md @@ -1,17 +1,16 @@ ### Array zip -Use `Math.max.apply` to get the longest array in the arguments. -Creates an array with that length as return value and use `Array.from` with a map-function to create an array of grouped elements. +Use `Math.max.apply()` to get the longest array in the arguments. +Creates an array with that length as return value and use `Array.from()` with a map-function to create an array of grouped elements. If lengths of the argument-arrays vary, `undefined` is used where no value could be found. ```js const zip = (...arrays) => { const maxLength = Math.max.apply(null, arrays.map(a => a.length)); return Array.from({length: maxLength}).map((_, i) => { - return Array.from({length: arrays.length}, (_, k) => arrays[k][i]) + return Array.from({length: arrays.length}, (_, k) => arrays[k][i]); }) } - //zip(['a', 'b'], [1, 2], [true, false]); -> [['a', 1, true], ['b', 2, false]] //zip(['a'], [1, 2], [true, false]); -> [['a', 1, true], [undefined, 2, false]] ``` diff --git a/snippets/deep-flatten-array.md b/snippets/deep-flatten-array.md index 1dffe860f..d33ff7e25 100644 --- a/snippets/deep-flatten-array.md +++ b/snippets/deep-flatten-array.md @@ -1,7 +1,8 @@ ### Deep flatten array Use recursion. -Use `[].concat()` and the spread operator `...` to flatten an array, and recursively flatten each element that is an array. +Use `Array.concat()` with an empty array (`[]`) and the spread operator (`...`) to flatten an array. +Rrecursively flatten each element that is an array. ```js const deepFlatten = arr => [].concat(...arr.map(v => Array.isArray(v) ? deepFlatten(v) : v)); diff --git a/snippets/pipe.md b/snippets/pipe.md index f46a32148..e5136777b 100644 --- a/snippets/pipe.md +++ b/snippets/pipe.md @@ -1,15 +1,14 @@ ### Pipe -Use `Array.reduce()` to perform left-to-right function composition. The first (leftmost) function can accept one or more arguments; the remaining functions must be unary. +Use `Array.reduce()` to perform left-to-right function composition. +The first (leftmost) function can accept one or more arguments; the remaining functions must be unary. ```js -const pipe = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))) +const pipe = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); /* const add5 = x => x + 5 -const multiply = (x, y) => x * y - +const multiply = (x, y) => x * y const multiplyAndAdd5 = pipe(multiply, add5) - multiplyAndAdd5(5, 2) -> 15 */ ``` diff --git a/snippets/takeRight.md b/snippets/take-right.md similarity index 83% rename from snippets/takeRight.md rename to snippets/take-right.md index 03fc634fa..1e7c55766 100644 --- a/snippets/takeRight.md +++ b/snippets/take-right.md @@ -1,4 +1,4 @@ -### takeRight +### Take right Use `Array.slice()` to create a slice of the array with `n` elements taken from the end. @@ -6,5 +6,4 @@ Use `Array.slice()` to create a slice of the array with `n` elements taken from const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length); // takeRight([1, 2, 3], 2) -> [ 2, 3 ] // takeRight([1, 2, 3]) -> [3] -// takeRight([1, 2, 3]) -> [] -``` \ No newline at end of file +``` diff --git a/tag_database b/tag_database index d1733c293..7e20b7516 100644 --- a/tag_database +++ b/tag_database @@ -2,7 +2,10 @@ anagrams-of-string-(with-duplicates):string array-concatenation:array array-difference:array array-intersection:array +array-sample:array array-union:array +array-without:array +array-zip:array average-of-array-of-numbers:array bottom-visible:browser capitalize-first-letter-of-every-word:string @@ -77,8 +80,8 @@ standard-deviation:math sum-of-array-of-numbers:array swap-values-of-two-variables:utility tail-of-list:array +take-right:array take:array -takeRight:array truncate-a-string:string unique-values-of-array:array URL-parameters:utility @@ -86,4 +89,3 @@ UUID-generator:utility validate-email:utility validate-number:utility value-or-default:utility -without:array From 2b4d7c6ee52adb792881f757043ef5102cb1981c Mon Sep 17 00:00:00 2001 From: Arjun Mahishi Date: Fri, 15 Dec 2017 16:30:12 +0530 Subject: [PATCH 10/24] Added snippet for array includes --- snippets/array-includes.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 snippets/array-includes.md diff --git a/snippets/array-includes.md b/snippets/array-includes.md new file mode 100644 index 000000000..c068d17b2 --- /dev/null +++ b/snippets/array-includes.md @@ -0,0 +1,10 @@ +### Array includes + +Use `slice()` to offset the array/string. `Array.indexOf()` returns `-1` if the sub-string/array dosen't contain the given `value`. + +```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 +``` \ No newline at end of file From e8293d89de4a515af9d02432254e1a858db16290 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Fri, 15 Dec 2017 13:06:53 +0200 Subject: [PATCH 11/24] Tag, lint, build --- README.md | 14 ++++++++++++++ snippets/array-includes.md | 6 +++--- tag_database | 1 + 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b8412a802..416266397 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ ### Array * [Array concatenation](#array-concatenation) * [Array difference](#array-difference) +* [Array includes](#array-includes) * [Array intersection](#array-intersection) * [Array sample](#array-sample) * [Array union](#array-union) @@ -142,6 +143,19 @@ 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 index c068d17b2..5ebcbc009 100644 --- a/snippets/array-includes.md +++ b/snippets/array-includes.md @@ -1,10 +1,10 @@ ### Array includes -Use `slice()` to offset the array/string. `Array.indexOf()` returns `-1` if the sub-string/array dosen't contain the given `value`. +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 -``` \ No newline at end of file +``` diff --git a/tag_database b/tag_database index 7e20b7516..67bdedd3c 100644 --- a/tag_database +++ b/tag_database @@ -1,6 +1,7 @@ anagrams-of-string-(with-duplicates):string array-concatenation:array array-difference:array +array-includes:array array-intersection:array array-sample:array array-union:array From cb488b39742979d664e883f84246b7c4d2208c5d Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Fri, 15 Dec 2017 13:15:21 +0200 Subject: [PATCH 12/24] Update write-json-to-file.md --- snippets/write-json-to-file.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/snippets/write-json-to-file.md b/snippets/write-json-to-file.md index 6a0ae21a0..5cff72064 100644 --- a/snippets/write-json-to-file.md +++ b/snippets/write-json-to-file.md @@ -1,9 +1,9 @@ ### Write a JSON to a file -Write a `json` object to a `.json` file. -```js -const fs = require('fs') +Use `fs.writeFile()`, template literals and `JSON.stringify()` to write a `json` object to a `.json` file. -const jsonToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 4)) +```js +const fs = require('fs'); +const jsonToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2)) // jsonToFile({test: "is passed"}, 'testJsonFile') ``` From 564486472469851e0ff92fb4045afbe795b7c991 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Fri, 15 Dec 2017 13:15:51 +0200 Subject: [PATCH 13/24] Update write-json-to-file.md --- snippets/write-json-to-file.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snippets/write-json-to-file.md b/snippets/write-json-to-file.md index 5cff72064..17de5a44e 100644 --- a/snippets/write-json-to-file.md +++ b/snippets/write-json-to-file.md @@ -5,5 +5,5 @@ Use `fs.writeFile()`, template literals and `JSON.stringify()` to write a `json` ```js const fs = require('fs'); const jsonToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2)) -// jsonToFile({test: "is passed"}, 'testJsonFile') +// jsonToFile({test: "is passed"}, 'testJsonFile') -> writes the object to 'testJsonFile.json' ``` From 25984a700e36340d2a6912c6701f7b9cc297a3d6 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Fri, 15 Dec 2017 13:33:46 +0200 Subject: [PATCH 14/24] Update shallow clone, tag, build --- README.md | 20 ++++++++++++++++++-- snippets/shallow-clone-object.md | 4 ++-- tag_database | 1 + 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 416266397..ace0e4e80 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,9 @@ ### Media * [Speech synthesis (experimental)](#speech-synthesis-experimental) +### Node +* [Write json to file](#write-json-to-file) + ### Object * [Object from key value pairs](#object-from-key-value-pairs) * [Object to key value pairs](#object-to-key-value-pairs) @@ -943,6 +946,19 @@ const speak = message => { // speak('Hello, World') -> plays the message ``` +[⬆ back to top](#table-of-contents) +## Node + +### Write a JSON to a file + +Use `fs.writeFile()`, template literals and `JSON.stringify()` to write a `json` object to a `.json` file. + +```js +const fs = require('fs'); +const jsonToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2)) +// jsonToFile({test: "is passed"}, 'testJsonFile') -> writes the object to 'testJsonFile.json' +``` + [⬆ back to top](#table-of-contents) ## Object @@ -970,10 +986,10 @@ const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]); ### Shallow clone object -Use the object `...spread` operator to spread the properties of the target object into the clone. +Use `Object.assign()` and an empty object (`{}`) to create a shallo clone of the original. ```js -const shallowClone = obj => ({ ...obj }); +const shallowClone = obj => Object.assign({}, obj); /* const a = { x: true, y: 1 }; const b = shallowClone(a); diff --git a/snippets/shallow-clone-object.md b/snippets/shallow-clone-object.md index c6873c0d8..f3536999f 100644 --- a/snippets/shallow-clone-object.md +++ b/snippets/shallow-clone-object.md @@ -1,9 +1,9 @@ ### Shallow clone object -Use the object `...spread` operator to spread the properties of the target object into the clone. +Use `Object.assign()` and an empty object (`{}`) to create a shallo clone of the original. ```js -const shallowClone = obj => ({ ...obj }); +const shallowClone = obj => Object.assign({}, obj); /* const a = { x: true, y: 1 }; const b = shallowClone(a); diff --git a/tag_database b/tag_database index 67bdedd3c..1a454936f 100644 --- a/tag_database +++ b/tag_database @@ -90,3 +90,4 @@ UUID-generator:utility validate-email:utility validate-number:utility value-or-default:utility +write-json-to-file:node From 5d11c699d56ca9615d927082a3a814fd30a7abc3 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Fri, 15 Dec 2017 13:42:31 +0200 Subject: [PATCH 15/24] Build --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index ace0e4e80..4e1b89453 100644 --- a/README.md +++ b/README.md @@ -1031,12 +1031,13 @@ const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperC ### Capitalize first letter -Use `slice(0,1)` and `toUpperCase()` to capitalize first letter, `slice(1)` to get the rest of the string. +Use destructuring and `toUpperCase()` to capitalize first letter, `...rest` to get array of characters after first letter and then `Array.join('')` to make it a string again. Omit the `lowerRest` parameter to keep the rest of the string intact, or set it to `true` to convert to lower case. ```js -const capitalize = (str, lowerRest = false) => - str.slice(0, 1).toUpperCase() + (lowerRest ? str.slice(1).toLowerCase() : str.slice(1)); +const capitalize = ([first,...rest], lowerRest = false) => + first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join('')); +// capitalize('myName') -> 'MyName' // capitalize('myName', true) -> 'Myname' ``` From a95b89a958f73994929136d76039f39f5eba984e Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Fri, 15 Dec 2017 13:50:09 +0200 Subject: [PATCH 16/24] Update remove.md --- snippets/remove.md | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/snippets/remove.md b/snippets/remove.md index 0a25e6f00..f9cfbc8a1 100644 --- a/snippets/remove.md +++ b/snippets/remove.md @@ -1,14 +1,13 @@ ### Remove -Remove elements from `arr` that are returns truthy. Use `Array.filter()` to finding the matching elements and `Array.reduce()` to remove elements using `Array.splice()`.The `func` is invoked with three arguments: (value, index, array). +Use `Array.filter()` to find array elements that return truthy values and `Array.reduce()` to remove elements using `Array.splice()`. +The `func` is invoked with three arguments (`value, index, array`). ```js const remove = (arr, func) => - Array.isArray(arr) ? - arr.filter(func).reduce((acc, val) => { - arr.splice(arr.indexOf(val), 1) - return acc.concat(val); + Array.isArray(arr) ? arr.filter(func).reduce((acc, val) => { + arr.splice(arr.indexOf(val), 1); return acc.concat(val); }, []) - : []; + : []; //remove([1, 2, 3, 4], n => n % 2 == 0) -> [2, 4] ``` From 1b682879083a47d08d2c9f78c17259c34f7c4186 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Fri, 15 Dec 2017 13:50:46 +0200 Subject: [PATCH 17/24] Update and rename remove.md to array-remove.md --- snippets/{remove.md => array-remove.md} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename snippets/{remove.md => array-remove.md} (96%) diff --git a/snippets/remove.md b/snippets/array-remove.md similarity index 96% rename from snippets/remove.md rename to snippets/array-remove.md index f9cfbc8a1..e08a4a02f 100644 --- a/snippets/remove.md +++ b/snippets/array-remove.md @@ -1,4 +1,4 @@ -### Remove +### Array remove Use `Array.filter()` to find array elements that return truthy values and `Array.reduce()` to remove elements using `Array.splice()`. The `func` is invoked with three arguments (`value, index, array`). From 11b948d43ffd61b317fa965f6c4d5a20b1bc2cd0 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Fri, 15 Dec 2017 13:51:06 +0200 Subject: [PATCH 18/24] Update array-concatenation.md --- snippets/array-concatenation.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snippets/array-concatenation.md b/snippets/array-concatenation.md index f441a0a17..40bf43c29 100644 --- a/snippets/array-concatenation.md +++ b/snippets/array-concatenation.md @@ -1,6 +1,6 @@ ### Array concatenation -Use `Array.concat()` to concatenate and array with any additional arrays and/or values, specified in `args`. +Use `Array.concat()` to concatenate an array with any additional arrays and/or values, specified in `args`. ```js const ArrayConcat = (arr, ...args) => [].concat(arr, ...args); From aef74133e239b1f0f73fb430557765b81b66afb5 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Fri, 15 Dec 2017 13:53:12 +0200 Subject: [PATCH 19/24] Tag and build --- README.md | 21 +++++++++++++++++++-- tag_database | 1 + 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4e1b89453..e6ada6c41 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ * [Array difference](#array-difference) * [Array includes](#array-includes) * [Array intersection](#array-intersection) +* [Array remove](#array-remove) * [Array sample](#array-sample) * [Array union](#array-union) * [Array without](#array-without) @@ -129,8 +130,8 @@ Use `Array.concat()` to concatenate an array with any additional arrays and/or values, specified in `args`. ```js -const arrayConcat = (arr, ...args) => arr.concat(...args); -// arrayConcat([1], 2, [3], [[4]]) -> [1,2,3,[4]] +const ArrayConcat = (arr, ...args) => [].concat(arr, ...args); +// ArrayConcat([1], [1, 2, 3, [4]]) -> [1, 2, 3, [4]] ``` [⬆ back to top](#table-of-contents) @@ -170,6 +171,22 @@ const intersection = (a, b) => { const s = new Set(b); return a.filter(x => s.ha [⬆ 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()`. +The `func` is invoked with three arguments (`value, index, array`). + +```js +const remove = (arr, func) => + Array.isArray(arr) ? arr.filter(func).reduce((acc, val) => { + arr.splice(arr.indexOf(val), 1); return acc.concat(val); + }, []) + : []; +//remove([1, 2, 3, 4], n => n % 2 == 0) -> [2, 4] +``` + +[⬆ back to top](#table-of-contents) + ### Array sample Use `Math.random()` to generate a random number, multiply it with `length` and round it of to the nearest whole number using `Math.floor()`. diff --git a/tag_database b/tag_database index 1a454936f..20b8fe94a 100644 --- a/tag_database +++ b/tag_database @@ -3,6 +3,7 @@ array-concatenation:array array-difference:array array-includes:array array-intersection:array +array-remove:array array-sample:array array-union:array array-without:array From 7f9a090537eb9a53e1ab8a90753415b642189530 Mon Sep 17 00:00:00 2001 From: David Wu Date: Fri, 15 Dec 2017 13:27:43 +0100 Subject: [PATCH 20/24] Update and rename hexadecimal-to-RGB.md to hexcode-to-RGB.md --- snippets/hexadecimal-to-RGB.md | 14 -------------- snippets/hexcode-to-RGB.md | 10 ++++++++++ 2 files changed, 10 insertions(+), 14 deletions(-) delete mode 100644 snippets/hexadecimal-to-RGB.md create mode 100644 snippets/hexcode-to-RGB.md diff --git a/snippets/hexadecimal-to-RGB.md b/snippets/hexadecimal-to-RGB.md deleted file mode 100644 index 73ee1d18d..000000000 --- a/snippets/hexadecimal-to-RGB.md +++ /dev/null @@ -1,14 +0,0 @@ -### Hexadecimal to RGB - -Converts hexadecimal colorcodes to RGB colorcodes by matching the hexidecimal (two-digit) red, green and blue values and -mapping their decimal equivalents to an array [r, g, b]. Works also with shorthand hex triplets such as "#05F". - -```js -const hexToRgb = hex => - hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i - ,(m, r, g, b) => '#' + r + r + g + g + b + b) - .substring(1).match(/.{2}/g) - .map(x => parseInt(x, 16)) -// hexToRgb('#27ae60') -> '[39, 174, 96]' -// hexToRgb('#aaa') -> '[170, 170, 170]' -``` diff --git a/snippets/hexcode-to-RGB.md b/snippets/hexcode-to-RGB.md new file mode 100644 index 000000000..9ca5c7447 --- /dev/null +++ b/snippets/hexcode-to-RGB.md @@ -0,0 +1,10 @@ +### Hexcode to RGB + +Converts hexadecimal colorcodes to RGB colorcodes by matching the hexidecimal (two-digit) red, green and blue values and +mapping their decimal equivalents to an array [r, g, b]. Returns a string `rgb(r,g,b)`. + +```js +const hexToRgb = hex => `rgb(${hex.slice(1).match(/.{2}/g).map(x => parseInt(x, 16)).join()})` +// hexToRgb('#27ae60') -> 'rgb(39,174,96)' +// hexToRgb('#aaa') -> '[170, 170, 170]' +``` From bbed04f0c93daf24a9d97505f276d36fa57ac2e1 Mon Sep 17 00:00:00 2001 From: Thomas Broadley Date: Fri, 15 Dec 2017 07:30:03 -0500 Subject: [PATCH 21/24] Fix typos --- CONTRIBUTING.md | 2 +- snippets/deep-flatten-array.md | 2 +- snippets/shallow-clone-object.md | 2 +- snippets/validate-email.md | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 618a99b1a..40e6f2a17 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -64,7 +64,7 @@ Here's what you can do to help: - If your snippet's code is short enough (around 80 characters), you can make it a single-line function (although not mandatory). Otherwise, use multiple lines. - Prefer using `Array` methods whenever possible. - Prefer `Array.concat()` instead of `Array.push()` when working with `Array.reduce()`. -- Use strict equality checking (`===` and `!==` instead of `==` and `!=`), unless you specificly have reason not to. +- Use strict equality checking (`===` and `!==` instead of `==` and `!=`), unless you specifically have reason not to. - Prefer using the ternary operator (`condition ? trueResult : falseResult`) instead of `if else` statements whenever possible. - Avoid nesting ternary operators (but you can do it if you feel like you should). - You should define multiple variables on the same line (e.g. `const x = 0, y = 0`) on the same line whenever possible. diff --git a/snippets/deep-flatten-array.md b/snippets/deep-flatten-array.md index d33ff7e25..8e9497d33 100644 --- a/snippets/deep-flatten-array.md +++ b/snippets/deep-flatten-array.md @@ -2,7 +2,7 @@ Use recursion. Use `Array.concat()` with an empty array (`[]`) and the spread operator (`...`) to flatten an array. -Rrecursively flatten each element that is an array. +Recursively flatten each element that is an array. ```js const deepFlatten = arr => [].concat(...arr.map(v => Array.isArray(v) ? deepFlatten(v) : v)); diff --git a/snippets/shallow-clone-object.md b/snippets/shallow-clone-object.md index f3536999f..456f38462 100644 --- a/snippets/shallow-clone-object.md +++ b/snippets/shallow-clone-object.md @@ -1,6 +1,6 @@ ### Shallow clone object -Use `Object.assign()` and an empty object (`{}`) to create a shallo clone of the original. +Use `Object.assign()` and an empty object (`{}`) to create a shallow clone of the original. ```js const shallowClone = obj => Object.assign({}, obj); diff --git a/snippets/validate-email.md b/snippets/validate-email.md index d83a41904..e168ac22b 100644 --- a/snippets/validate-email.md +++ b/snippets/validate-email.md @@ -1,6 +1,6 @@ ### Validate email -Use a regular experssion to check if the email is valid. +Use a regular expression to check if the email is valid. Returns `true` if email is valid, `false` if not. ```js From 3d6b44631a35691339011af6f437379a4e47eccf Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Fri, 15 Dec 2017 14:33:12 +0200 Subject: [PATCH 22/24] Typos in README --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index e6ada6c41..4dc791572 100644 --- a/README.md +++ b/README.md @@ -292,7 +292,7 @@ const countOccurrences = (arr, value) => arr.reduce((a, v) => v === value ? a + Use recursion. Use `Array.concat()` with an empty array (`[]`) and the spread operator (`...`) to flatten an array. -Rrecursively flatten each element that is an array. +Recursively flatten each element that is an array. ```js const deepFlatten = arr => [].concat(...arr.map(v => Array.isArray(v) ? deepFlatten(v) : v)); @@ -1003,7 +1003,7 @@ const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]); ### Shallow clone object -Use `Object.assign()` and an empty object (`{}`) to create a shallo clone of the original. +Use `Object.assign()` and an empty object (`{}`) to create a shallow clone of the original. ```js const shallowClone = obj => Object.assign({}, obj); @@ -1330,7 +1330,7 @@ const uuid = _ => ### Validate email -Use a regular experssion to check if the email is valid. +Use a regular expression to check if the email is valid. Returns `true` if email is valid, `false` if not. ```js From 92ce0e528f357599ffdac4a5e191e19cc89847d4 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Fri, 15 Dec 2017 14:36:23 +0200 Subject: [PATCH 23/24] Update hexcode-to-RGB.md --- snippets/hexcode-to-RGB.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/snippets/hexcode-to-RGB.md b/snippets/hexcode-to-RGB.md index 9ca5c7447..852a25ff8 100644 --- a/snippets/hexcode-to-RGB.md +++ b/snippets/hexcode-to-RGB.md @@ -1,10 +1,8 @@ ### Hexcode to RGB -Converts hexadecimal colorcodes to RGB colorcodes by matching the hexidecimal (two-digit) red, green and blue values and -mapping their decimal equivalents to an array [r, g, b]. Returns a string `rgb(r,g,b)`. +Use `Array.slice()`, `Array.map()` and `match()` to convert a hexadecimal colorcode (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)' -// hexToRgb('#aaa') -> '[170, 170, 170]' ``` From 7d874b0862325a96ff506340486f2db39e37f53a Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Fri, 15 Dec 2017 14:37:51 +0200 Subject: [PATCH 24/24] Tag and build --- README.md | 12 ++++++++++++ tag_database | 1 + 2 files changed, 13 insertions(+) diff --git a/README.md b/README.md index 4dc791572..776d746ef 100644 --- a/README.md +++ b/README.md @@ -104,6 +104,7 @@ ### Utility * [Escape regular expression](#escape-regular-expression) * [Get native type of value](#get-native-type-of-value) +* [Hexcode to RGB](#hexcode-to-rgb) * [Is array](#is-array) * [Is boolean](#is-boolean) * [Is function](#is-function) @@ -1136,6 +1137,17 @@ const getType = v => [⬆ back to top](#table-of-contents) +### Hexcode to RGB + +Use `Array.slice()`, `Array.map()` and `match()` to convert a hexadecimal colorcode (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)' +``` + +[⬆ back to top](#table-of-contents) + ### Is array Use `Array.isArray()` to check if a value is classified as an array. diff --git a/tag_database b/tag_database index 20b8fe94a..3acb709f1 100644 --- a/tag_database +++ b/tag_database @@ -42,6 +42,7 @@ greatest-common-divisor-(GCD):math group-by:array hamming-distance:math head-of-list:array +hexcode-to-RGB:utility initial-of-list:array initialize-array-with-range:array initialize-array-with-values:array