diff --git a/README.md b/README.md index 7160b9afb..e6ada6c41 100644 --- a/README.md +++ b/README.md @@ -12,8 +12,13 @@ ### 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) * [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 +44,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) @@ -78,6 +84,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) @@ -121,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) @@ -138,6 +147,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`. @@ -149,6 +171,34 @@ 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()`. +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 +210,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 +261,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 +291,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 +550,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 +726,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) @@ -864,6 +963,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 @@ -891,10 +1003,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); @@ -936,12 +1048,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' ``` diff --git a/snippets/array-concatenation.md b/snippets/array-concatenation.md index 992036905..40bf43c29 100644 --- a/snippets/array-concatenation.md +++ b/snippets/array-concatenation.md @@ -3,6 +3,6 @@ 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]] ``` diff --git a/snippets/array-includes.md b/snippets/array-includes.md new file mode 100644 index 000000000..5ebcbc009 --- /dev/null +++ b/snippets/array-includes.md @@ -0,0 +1,10 @@ +### 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 +``` diff --git a/snippets/array-remove.md b/snippets/array-remove.md new file mode 100644 index 000000000..e08a4a02f --- /dev/null +++ b/snippets/array-remove.md @@ -0,0 +1,13 @@ +### 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] +``` diff --git a/snippets/array-sample.md b/snippets/array-sample.md new file mode 100644 index 000000000..9de5c5ae0 --- /dev/null +++ b/snippets/array-sample.md @@ -0,0 +1,9 @@ +### 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 +``` diff --git a/snippets/array-without.md b/snippets/array-without.md new file mode 100644 index 000000000..dd657fe2a --- /dev/null +++ b/snippets/array-without.md @@ -0,0 +1,9 @@ +### 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 ] +``` diff --git a/snippets/array-zip.md b/snippets/array-zip.md new file mode 100644 index 000000000..6c9a2491b --- /dev/null +++ b/snippets/array-zip.md @@ -0,0 +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. +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]] +``` diff --git a/snippets/capitalize-first-letter.md b/snippets/capitalize-first-letter.md index 61f73b6a7..edbb04b02 100644 --- a/snippets/capitalize-first-letter.md +++ b/snippets/capitalize-first-letter.md @@ -1,10 +1,11 @@ ### 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' ``` diff --git a/snippets/chunk-array.md b/snippets/chunk-array.md index c14bf269d..ba3e5e42e 100644 --- a/snippets/chunk-array.md +++ b/snippets/chunk-array.md @@ -7,5 +7,5 @@ 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]] ``` diff --git a/snippets/deep-flatten-array.md b/snippets/deep-flatten-array.md index c350d848c..d33ff7e25 100644 --- a/snippets/deep-flatten-array.md +++ b/snippets/deep-flatten-array.md @@ -1,10 +1,10 @@ ### 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] ``` diff --git a/snippets/pipe.md b/snippets/pipe.md index c61ec042c..e5136777b 100644 --- a/snippets/pipe.md +++ b/snippets/pipe.md @@ -1,8 +1,14 @@ ### 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 +*/ ``` 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/snippets/take-right.md b/snippets/take-right.md new file mode 100644 index 000000000..1e7c55766 --- /dev/null +++ b/snippets/take-right.md @@ -0,0 +1,9 @@ +### 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] +``` diff --git a/snippets/write-json-to-file.md b/snippets/write-json-to-file.md new file mode 100644 index 000000000..17de5a44e --- /dev/null +++ b/snippets/write-json-to-file.md @@ -0,0 +1,9 @@ +### 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' +``` diff --git a/tag_database b/tag_database index b2535a484..20b8fe94a 100644 --- a/tag_database +++ b/tag_database @@ -1,8 +1,13 @@ anagrams-of-string-(with-duplicates):string array-concatenation:array array-difference:array +array-includes:array array-intersection:array +array-remove: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,6 +82,7 @@ standard-deviation:math sum-of-array-of-numbers:array swap-values-of-two-variables:utility tail-of-list:array +take-right:array take:array truncate-a-string:string unique-values-of-array:array @@ -85,3 +91,4 @@ UUID-generator:utility validate-email:utility validate-number:utility value-or-default:utility +write-json-to-file:node