diff --git a/snippets/JSONToDate.md b/snippets/JSONToDate.md index c5fa32175..311da31e7 100644 --- a/snippets/JSONToDate.md +++ b/snippets/JSONToDate.md @@ -7,7 +7,7 @@ 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() }` + return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`; }; // JSONToDate(/Date(1489525200000)/) -> "14/3/2017" ``` diff --git a/snippets/JSONToFile.md b/snippets/JSONToFile.md index 3677fc5e3..984e516b6 100644 --- a/snippets/JSONToFile.md +++ b/snippets/JSONToFile.md @@ -6,6 +6,6 @@ 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)) +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/snippets/arrayGcd.md b/snippets/arrayGcd.md index 39a154059..fde889d05 100644 --- a/snippets/arrayGcd.md +++ b/snippets/arrayGcd.md @@ -5,10 +5,10 @@ Calculates the greatest common denominator (gcd) of an array of numbers. Use `Array.reduce()` and the `gcd` formula (uses recursion) to calculate the greatest common denominator of an array of numbers. ```js -const arrayGcd = arr =>{ +const arrayGcd = arr => { const gcd = (x, y) => !y ? x : gcd(y, x % y); - return arr.reduce((a,b) => gcd(a,b)); -} + return arr.reduce((a, b) => gcd(a, b)); +}; // arrayGcd([1,2,3,4,5]) -> 1 // arrayGcd([4,8,12]) -> 4 ``` diff --git a/snippets/arrayLcm.md b/snippets/arrayLcm.md index 8d4e593fb..42cb61906 100644 --- a/snippets/arrayLcm.md +++ b/snippets/arrayLcm.md @@ -5,11 +5,11 @@ Calculates the lowest common multiple (lcm) of an array of numbers. Use `Array.reduce()` and the `lcm` formula (uses recursion) to calculate the lowest common multiple of an array of numbers. ```js -const arrayLcm = arr =>{ +const arrayLcm = arr => { const gcd = (x, y) => !y ? x : gcd(y, x % y); - const lcm = (x, y) => (x*y)/gcd(x, y); - return arr.reduce((a,b) => lcm(a,b)); -} + const lcm = (x, y) => (x * y) / gcd(x, y); + return arr.reduce((a, b) => lcm(a, b)); +}; // arrayLcm([1,2,3,4,5]) -> 60 // arrayLcm([4,8,12]) -> 24 ``` diff --git a/snippets/arrayToHtmlList.md b/snippets/arrayToHtmlList.md index bf5ba5721..6577ff663 100644 --- a/snippets/arrayToHtmlList.md +++ b/snippets/arrayToHtmlList.md @@ -5,6 +5,6 @@ Converts the given array elements into `
  • ` tags and appends them to the list Use `Array.map()` and `document.querySelector()` to create a list of html tags. ```js -const arrayToHtmlList = (arr, listID) => arr.map(item => document.querySelector("#"+listID).innerHTML+=`
  • ${item}
  • `); +const arrayToHtmlList = (arr, listID) => arr.map(item => document.querySelector('#' + listID).innerHTML += `
  • ${item}
  • `); // arrayToHtmlList(['item 1', 'item 2'],'myListID') ``` diff --git a/snippets/call.md b/snippets/call.md index a7aec4808..1cb0d4758 100644 --- a/snippets/call.md +++ b/snippets/call.md @@ -5,7 +5,7 @@ Given a key and a set of arguments, call them when given a context. Primarily us Use a closure to call a stored key with stored arguments. ```js -const call = ( key, ...args ) => context => context[ key ]( ...args ); +const call = (key, ...args) => context => context[ key ](...args); /* Promise.resolve( [ 1, 2, 3 ] ).then( call('map', x => 2 * x ) ).then( console.log ) //[ 2, 4, 6 ] const map = call.bind(null, 'map') diff --git a/snippets/capitalize.md b/snippets/capitalize.md index d085a3034..9991e279e 100644 --- a/snippets/capitalize.md +++ b/snippets/capitalize.md @@ -6,7 +6,7 @@ Use destructuring and `toUpperCase()` to capitalize first letter, `...rest` to g Omit the `lowerRest` parameter to keep the rest of the string intact, or set it to `true` to convert to lowercase. ```js -const capitalize = ([first,...rest], lowerRest = false) => +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/clampNumber.md b/snippets/clampNumber.md index d1bf9d64f..a71e4136e 100644 --- a/snippets/clampNumber.md +++ b/snippets/clampNumber.md @@ -8,9 +8,9 @@ Otherwise, return the nearest number in the range. ```js const clampNumber = (num, lower, upper) => { - if(lower > upper) upper = [lower, lower = upper][0]; - return (num>=lower && num<=upper) ? num : ((num < lower) ? lower : upper) -} + if (lower > upper) upper = [lower, lower = upper][0]; + return (num >= lower && num <= upper) ? num : ((num < lower) ? lower : upper); +}; // clampNumber(2, 3, 5) -> 3 // clampNumber(1, -1, -5) -> -1 // clampNumber(3, 2, 4) -> 3 diff --git a/snippets/cleanObj.md b/snippets/cleanObj.md index 82cfe4441..3ce8d2cdd 100644 --- a/snippets/cleanObj.md +++ b/snippets/cleanObj.md @@ -13,9 +13,9 @@ const cleanObj = (obj, keysToKeep = [], childIndicator) => { } else if (!keysToKeep.includes(key)) { delete obj[key]; } -  }); +  }); return obj; -} +}; /* const testObj = {a: 1, b: 2, children: {a: 1, b: 2}} cleanObj(testObj, ["a"],"children") // { a: 1, children : { a: 1}} diff --git a/snippets/coalesce.md b/snippets/coalesce.md index 22271dc68..1002df4d2 100644 --- a/snippets/coalesce.md +++ b/snippets/coalesce.md @@ -5,6 +5,6 @@ Returns the first non-null/undefined argument. Use `Array.find()` to return the first non `null`/`undefined` argument. ```js -const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_)) +const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_)); // coalesce(null,undefined,"",NaN, "Waldo") -> "" ``` diff --git a/snippets/collectInto.md b/snippets/collectInto.md index c9a823d3d..69c036764 100644 --- a/snippets/collectInto.md +++ b/snippets/collectInto.md @@ -5,7 +5,7 @@ Changes a function that accepts an array into a variadic function. Given a function, return a closure that collects all inputs into an array-accepting function. ```js -const collectInto = fn => ( ...args ) => fn( args ); +const collectInto = fn => (...args) => fn(args); /* const Pall = collectInto( Promise.all.bind(Promise) ) let p1 = Promise.resolve(1) diff --git a/snippets/detectDeviceType.md b/snippets/detectDeviceType.md index b2822a458..291e148c5 100644 --- a/snippets/detectDeviceType.md +++ b/snippets/detectDeviceType.md @@ -5,7 +5,7 @@ Detects wether the website is being opened in a mobile device or a desktop/lapto Use a regular expression to test the `navigator.userAgent` property to figure out if the device is a mobile device or a desktop/laptop. ```js -const detectDeviceType = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? "Mobile" : "Desktop"; +const detectDeviceType = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? 'Mobile' : 'Desktop'; // detectDeviceType() -> "Mobile" // detectDeviceType() -> "Desktop" ``` diff --git a/snippets/differenceWith.md b/snippets/differenceWith.md index ba4aac0ec..02f686f4b 100644 --- a/snippets/differenceWith.md +++ b/snippets/differenceWith.md @@ -5,6 +5,6 @@ Filters out all values from an array for which the comparator function does not Use `Array.filter()` and `Array.find()` to find the appropriate values. ```js -const differenceWith = (arr, val, comp) => arr.filter(a => !val.find(b => comp(a, b))) +const differenceWith = (arr, val, comp) => arr.filter(a => !val.find(b => comp(a, b))); // differenceWith([1, 1.2, 1.5, 3], [1.9, 3], (a,b) => Math.round(a) == Math.round(b)) -> [1, 1.2] ``` diff --git a/snippets/digitize.md b/snippets/digitize.md index f856c8369..6a48fafcb 100644 --- a/snippets/digitize.md +++ b/snippets/digitize.md @@ -6,6 +6,6 @@ Convert the number to a string, using spread operators in ES6(`[...string]`) bui Use `Array.map()` and `parseInt()` to transform each value to an integer. ```js -const digitize = n => [...''+n].map(i => parseInt(i)); +const digitize = n => [...'' + n].map(i => parseInt(i)); // digitize(2334) -> [2, 3, 3, 4] ``` diff --git a/snippets/dropRight.md b/snippets/dropRight.md index a39613a14..3e6716f0e 100644 --- a/snippets/dropRight.md +++ b/snippets/dropRight.md @@ -6,7 +6,7 @@ Use `Array.slice()` to slice the remove the specified number of elements from th ```js const dropRight = (arr, n = 1) => arr.slice(0, -n); -//dropRight([1,2,3]) -> [1,2] -//dropRight([1,2,3], 2) -> [1] -//dropRight([1,2,3], 42) -> [] +// dropRight([1,2,3]) -> [1,2] +// dropRight([1,2,3], 2) -> [1] +// dropRight([1,2,3], 42) -> [] ``` diff --git a/snippets/extendHex.md b/snippets/extendHex.md index 8c7773c5e..a134ebd7b 100644 --- a/snippets/extendHex.md +++ b/snippets/extendHex.md @@ -6,7 +6,7 @@ Use `Array.map()`, `split()` and `Array.join()` to join the mapped array for con `String.slice()` is used to remove `#` from string start since it's added once. ```js const extendHex = shortHex => - '#' + shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split('').map(x => x+x).join('') + '#' + shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split('').map(x => x + x).join(''); // extendHex('#03f') -> '#0033ff' // extendHex('05a') -> '#0055aa' ``` diff --git a/snippets/factorial.md b/snippets/factorial.md index aaedd7520..e0afbd2c3 100644 --- a/snippets/factorial.md +++ b/snippets/factorial.md @@ -9,7 +9,7 @@ Throws an exception if `n` is a negative number. ```js const factorial = n => - n < 0 ? (() => { throw new TypeError('Negative numbers are not allowed!') })() + n < 0 ? (() => { throw new TypeError('Negative numbers are not allowed!'); })() : n <= 1 ? 1 : n * factorial(n - 1); // factorial(6) -> 720 ``` diff --git a/snippets/fibonacciCountUntilNum.md b/snippets/fibonacciCountUntilNum.md index 12fffbfb6..8cf904ef0 100644 --- a/snippets/fibonacciCountUntilNum.md +++ b/snippets/fibonacciCountUntilNum.md @@ -6,6 +6,6 @@ Use a mathematical formula to calculate the number of fibonacci numbers until `n ```js const fibonacciCountUntilNum = num => - Math.ceil(Math.log(num * Math.sqrt(5) + 1/2) / Math.log((Math.sqrt(5)+1)/2)); + Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2)); // fibonacciCountUntilNum(10) -> 7 ``` diff --git a/snippets/fibonacciUntilNum.md b/snippets/fibonacciUntilNum.md index 55df575d0..5e1b2c9d7 100644 --- a/snippets/fibonacciUntilNum.md +++ b/snippets/fibonacciUntilNum.md @@ -8,8 +8,8 @@ Uses a mathematical formula to calculate the length of the array required. ```js const fibonacciUntilNum = num => { - let n = Math.ceil(Math.log(num * Math.sqrt(5) + 1/2) / Math.log((Math.sqrt(5)+1)/2)); + let n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2)); return Array.from({ length: n}).reduce((acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), []); -} +}; // fibonacciUntilNum(15) -> [0,1,1,2,3,5,8,13] ``` diff --git a/snippets/flatten.md b/snippets/flatten.md index f070f2cae..0efd29071 100644 --- a/snippets/flatten.md +++ b/snippets/flatten.md @@ -5,6 +5,6 @@ Flattens an array. Use a new array and concatenate it with the spread input array causing a shallow denesting of any contained arrays. ```js -const flatten = arr => [ ].concat( ...arr ); +const flatten = arr => [ ].concat(...arr); // flatten([1,[2],3,4]) -> [1,2,3,4] ``` diff --git a/snippets/flip.md b/snippets/flip.md index 502cef288..004d838d2 100644 --- a/snippets/flip.md +++ b/snippets/flip.md @@ -5,7 +5,7 @@ Flip takes a function as an argument, then makes the first argument the last Return a closure that takes variadic inputs, and splices the last argument to make it the first argument before applying the rest. ```js -const flip = fn => (...args) => fn(args.pop(), ...args) +const flip = fn => (...args) => fn(args.pop(), ...args); /* let a = {name: 'John Smith'} let b = {} diff --git a/snippets/hexToRGB.md b/snippets/hexToRGB.md index 66c95fd3a..c86004039 100644 --- a/snippets/hexToRGB.md +++ b/snippets/hexToRGB.md @@ -10,14 +10,13 @@ const hexToRGB = hex => { if (h.length === 3) h = [...h].map(x => x + x).join(''); else if (h.length === 8) alpha = true; h = parseInt(h, 16); - return 'rgb' + (alpha ? 'a' : '') + '(' - + (h >>> (alpha ? 24 : 16)) + ', ' - + ((h & (alpha ? 0x00ff0000 : 0x00ff00)) >>> (alpha ? 16 : 8)) + ', ' - + ((h & (alpha ? 0x0000ff00 : 0x0000ff)) >>> (alpha ? 8 : 0)) - + (alpha ? `, ${(h & 0x000000ff)}` : '') + ')'; + return 'rgb' + (alpha ? 'a' : '') + '(' + + (h >>> (alpha ? 24 : 16)) + ', ' + + ((h & (alpha ? 0x00ff0000 : 0x00ff00)) >>> (alpha ? 16 : 8)) + ', ' + + ((h & (alpha ? 0x0000ff00 : 0x0000ff)) >>> (alpha ? 8 : 0)) + + (alpha ? `, ${(h & 0x000000ff)}` : '') + ')'; }; // hexToRGB('#27ae60ff') -> 'rgba(39, 174, 96, 255)' // hexToRGB('27ae60') -> 'rgb(39, 174, 96)' // hexToRGB('#fff') -> 'rgb(255, 255, 255)' - ``` diff --git a/snippets/httpsRedirect.md b/snippets/httpsRedirect.md index b1b851320..7cf087584 100644 --- a/snippets/httpsRedirect.md +++ b/snippets/httpsRedirect.md @@ -6,6 +6,6 @@ Use `location.protocol` to get the protocol currently being used. If it's not HT ```js const httpsRedirect = () => { - if(location.protocol !== "https:") location.replace("https://" + location.href.split("//")[1]); -} + if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]); +}; ``` diff --git a/snippets/inRange.md b/snippets/inRange.md index 5089393dc..ab4a610e7 100644 --- a/snippets/inRange.md +++ b/snippets/inRange.md @@ -6,10 +6,10 @@ Use arithmetic comparison to check if the given number is in the specified range If the second parameter, `end`, is not specified, the range is considered to be from `0` to `start`. ```js -const inRange = (n, start, end=null) => { - if(end && start > end) end = [start, start=end][0]; - return (end == null) ? (n>=0 && n=start && n { + if (end && start > end) end = [start, start = end][0]; + return (end == null) ? (n >= 0 && n < start) : (n >= start && n < end); +}; // inRange(3, 2, 5) -> true // inRange(3, 4) -> true // inRange(2, 3, 5) -> false diff --git a/snippets/initializeArrayWithRange.md b/snippets/initializeArrayWithRange.md index c3ef5a0a0..3fefca2ed 100644 --- a/snippets/initializeArrayWithRange.md +++ b/snippets/initializeArrayWithRange.md @@ -6,7 +6,7 @@ Use `Array((end + 1) - start)` to create an array of the desired length, `Array. You can omit `start` to use a default value of `0`. ```js -const initializeArrayWithRange = (end, start = 0) => +const initializeArrayWithRange = (end, start = 0) => Array.from({ length: (end + 1) - start }).map((v, i) => i + start); // initializeArrayWithRange(5) -> [0,1,2,3,4,5] // initializeArrayWithRange(7, 3) -> [3,4,5,6,7] diff --git a/snippets/isArmstrongNumber.md b/snippets/isArmstrongNumber.md index 139de9d72..a680d607e 100644 --- a/snippets/isArmstrongNumber.md +++ b/snippets/isArmstrongNumber.md @@ -5,8 +5,8 @@ Checks if the given number is an Armstrong number or not. Convert the given number into an array of digits. Use `Math.pow()` to get the appropriate power for each digit and sum them up. If the sum is equal to the number itself, return `true` otherwise `false`. ```js -const isArmstrongNumber = digits => - ( arr => arr.reduce( ( a, d ) => a + Math.pow( parseInt( d ), arr.length ), 0 ) == digits ? true : false )( ( digits+'' ).split( '' ) ); +const isArmstrongNumber = digits => + (arr => arr.reduce((a, d) => a + Math.pow(parseInt(d), arr.length), 0) == digits)((digits + '').split('')); // isArmstrongNumber(1634) -> true // isArmstrongNumber(371) -> true // isArmstrongNumber(56) -> false diff --git a/snippets/lcm.md b/snippets/lcm.md index 73b9c43c8..ef8ea7fdc 100644 --- a/snippets/lcm.md +++ b/snippets/lcm.md @@ -6,9 +6,9 @@ Use the greatest common divisor (GCD) formula and `Math.abs()` to determine the The GCD formula uses recursion. ```js -const lcm = (x,y) => { +const lcm = (x, y) => { const gcd = (x, y) => !y ? x : gcd(y, x % y); - return Math.abs(x*y)/(gcd(x,y)); + return Math.abs(x * y) / (gcd(x, y)); }; // lcm(12,7) -> 84 ``` diff --git a/snippets/mapObject.md b/snippets/mapObject.md index eb5ea736f..f9d65ee32 100644 --- a/snippets/mapObject.md +++ b/snippets/mapObject.md @@ -5,8 +5,8 @@ Maps the values of an array to an object using a function, where the key-value p Use an anonymous inner function scope to declare an undefined memory space, using closures to store a return value. Use a new `Array` to store the array with a map of the function over its data set and a comma operator to return a second step, without needing to move from one context to another (due to closures and order of operations). ```js -const mapObject = (arr, fn) => - (a => (a = [arr, arr.map(fn)], a[0].reduce( (acc,val,ind) => (acc[val] = a[1][ind], acc), {}) )) ( ); +const mapObject = (arr, fn) => + (a => (a = [arr, arr.map(fn)], a[0].reduce((acc, val, ind) => (acc[val] = a[1][ind], acc), {})))(); /* const squareIt = arr => mapObject(arr, a => a*a) squareIt([1,2,3]) // { 1: 1, 2: 4, 3: 9 } diff --git a/snippets/nthElement.md b/snippets/nthElement.md index ae472eb38..be1da2ce0 100644 --- a/snippets/nthElement.md +++ b/snippets/nthElement.md @@ -7,7 +7,7 @@ If the index is out of bounds, return `[]`. Omit the second argument, `n`, to get the first element of the array. ```js -const nthElement = (arr, n=0) => (n>0? arr.slice(n,n+1) : arr.slice(n))[0]; +const nthElement = (arr, n = 0) => (n > 0 ? arr.slice(n, n + 1) : arr.slice(n))[0]; // nthElement(['a','b','c'],1) -> 'b' // nthElement(['a','b','b'],-3) -> 'a' ``` diff --git a/snippets/primes.md b/snippets/primes.md index 81e8f2999..109192e7c 100644 --- a/snippets/primes.md +++ b/snippets/primes.md @@ -6,11 +6,11 @@ Generate an array from `2` to the given number. Use `Array.filter()` to filter o ```js const primes = num => { - let arr = Array.from({length:num-1}).map((x,i)=> i+2), - sqroot = Math.floor(Math.sqrt(num)), - numsTillSqroot = Array.from({length:sqroot-1}).map((x,i)=> i+2); - numsTillSqroot.forEach(x => arr = arr.filter(y => ((y%x)!==0)||(y==x))); - return arr; -} -// primes(10) -> [2,3,5,7] + let arr = Array.from({length: num - 1}).map((x, i) => i + 2), + sqroot = Math.floor(Math.sqrt(num)), + numsTillSqroot = Array.from({length: sqroot - 1}).map((x, i) => i + 2); + numsTillSqroot.forEach(x => arr = arr.filter(y => ((y % x) !== 0) || (y == x))); + return arr; +}; +// primes(10) -> [2,3,5,7] ``` diff --git a/snippets/pull.md b/snippets/pull.md index d7d0412c0..3848e27dd 100644 --- a/snippets/pull.md +++ b/snippets/pull.md @@ -11,7 +11,7 @@ _(For a snippet that does not mutate the original array see [`without`](#without const pull = (arr, ...args) => { let argState = Array.isArray(args[0]) ? args[0] : args; let pulled = arr.filter((v, i) => !argState.includes(v)); - arr.length = 0; + arr.length = 0; pulled.forEach(v => arr.push(v)); }; diff --git a/snippets/pullAtIndex.md b/snippets/pullAtIndex.md index 260d7b634..e848cc7c7 100644 --- a/snippets/pullAtIndex.md +++ b/snippets/pullAtIndex.md @@ -10,11 +10,11 @@ Use `Array.push()` to keep track of pulled values const pullAtIndex = (arr, pullArr) => { let removed = []; let pulled = arr.map((v, i) => pullArr.includes(i) ? removed.push(v) : v) - .filter((v, i) => !pullArr.includes(i)) - arr.length = 0; + .filter((v, i) => !pullArr.includes(i)); + arr.length = 0; pulled.forEach(v => arr.push(v)); return removed; -} +}; // let myArray = ['a', 'b', 'c', 'd']; // let pulled = pullAtIndex(myArray, [1, 3]); diff --git a/snippets/pullAtValue.md b/snippets/pullAtValue.md index 52e1eac21..c092933e4 100644 --- a/snippets/pullAtValue.md +++ b/snippets/pullAtValue.md @@ -8,13 +8,13 @@ Use `Array.push()` to keep track of pulled values ```js const pullAtValue = (arr, pullArr) => { - let removed = [], + let removed = [], pushToRemove = arr.forEach((v, i) => pullArr.includes(v) ? removed.push(v) : v), mutateTo = arr.filter((v, i) => !pullArr.includes(v)); arr.length = 0; mutateTo.forEach(v => arr.push(v)); return removed; -} +}; /* let myArray = ['a', 'b', 'c', 'd']; let pulled = pullAtValue(myArray, ['b', 'd']); diff --git a/snippets/randomHexColor.md b/snippets/randomHexColor.md index 846239670..f7cdbc26e 100644 --- a/snippets/randomHexColor.md +++ b/snippets/randomHexColor.md @@ -6,10 +6,10 @@ Use `Math.random` to generate a random 24-bit(6x4bits) hexadecimal number. Use b ```js const randomHexColor = () => { - let n = (Math.random()*0xfffff|0).toString(16); - return '#' + (n.length !== 6 - ? (Math.random()*0xf|0).toString(16) + n : n); -} + let n = (Math.random() * 0xfffff | 0).toString(16); + return '#' + (n.length !== 6 + ? (Math.random() * 0xf | 0).toString(16) + n : n); +}; // randomHexColorCode() -> "#e34155" // randomHexColorCode() -> "#fd73a6" // randomHexColorCode() -> "#4144c6" diff --git a/snippets/remove.md b/snippets/remove.md index 34b10aa24..25606c21b 100644 --- a/snippets/remove.md +++ b/snippets/remove.md @@ -9,7 +9,7 @@ The `func` is invoked with three arguments (`value, index, array`). 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/repeatString.md b/snippets/repeatString.md index 888965713..c7478acb2 100644 --- a/snippets/repeatString.md +++ b/snippets/repeatString.md @@ -5,9 +5,9 @@ Repeats a string n times using `String.repeat()` If no string is provided the default is `""` and the default number of times is 2. ```js -const repeatString = (str="",num=2) => { - return num >= 0 ? str.repeat(num) : str; -} +const repeatString = (str = '', num = 2) => { + return num >= 0 ? str.repeat(num) : str; +}; // repeatString("abc",3) -> 'abcabcabc' // repeatString("abc") -> 'abcabc' ``` diff --git a/snippets/round.md b/snippets/round.md index 7675c734f..81e90dfe0 100644 --- a/snippets/round.md +++ b/snippets/round.md @@ -6,6 +6,6 @@ Use `Math.round()` and template literals to round the number to the specified nu Omit the second argument, `decimals` to round to an integer. ```js -const round = (n, decimals=0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`); +const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`); // round(1.005, 2) -> 1.01 ``` diff --git a/snippets/symmetricDifference.md b/snippets/symmetricDifference.md index a25bb52ef..596adf28a 100644 --- a/snippets/symmetricDifference.md +++ b/snippets/symmetricDifference.md @@ -8,6 +8,6 @@ Create a `Set` from each array, then use `Array.filter()` on each of them to onl 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/snippets/timeTaken.md b/snippets/timeTaken.md index 2c7bc181f..05b16fb46 100644 --- a/snippets/timeTaken.md +++ b/snippets/timeTaken.md @@ -6,8 +6,8 @@ Use `console.time()` and `console.timeEnd()` to measure the difference between t ```js const timeTaken = callback => { - console.time('timeTaken'); const r = callback(); - console.timeEnd('timeTaken'); return r; + console.time('timeTaken'); const r = callback(); + console.timeEnd('timeTaken'); return r; }; // timeTaken(() => Math.pow(2, 10)) -> 1024 // (logged): timeTaken: 0.02099609375ms diff --git a/snippets/toCamelCase.md b/snippets/toCamelCase.md index 5100441af..c3c78e8e9 100644 --- a/snippets/toCamelCase.md +++ b/snippets/toCamelCase.md @@ -8,10 +8,10 @@ For more detailed explanation of this Regex, [visit this Site](https://regex101. ```js const toCamelCase = str => { let s = str && str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g) - .map(x => x.slice(0,1).toUpperCase() + x.slice(1).toLowerCase()) + .map(x => x.slice(0, 1).toUpperCase() + x.slice(1).toLowerCase()) .join(''); - return s.slice(0,1).toLowerCase() + s.slice(1) - } + return s.slice(0, 1).toLowerCase() + s.slice(1); +}; // toCamelCase("some_database_field_name") -> 'someDatabaseFieldName' // toCamelCase("Some label that needs to be camelized") -> 'someLabelThatNeedsToBeCamelized' // toCamelCase("some-javascript-property") -> 'someJavascriptProperty' diff --git a/snippets/toDecimalMark.md b/snippets/toDecimalMark.md index 94e821376..b05429817 100644 --- a/snippets/toDecimalMark.md +++ b/snippets/toDecimalMark.md @@ -3,6 +3,6 @@ Use `toLocaleString()` to convert a float-point arithmetic to the [Decimal mark](https://en.wikipedia.org/wiki/Decimal_mark) form. It makes a comma separated string from a number. ```js -const toDecimalMark = num => num.toLocaleString("en-US"); +const toDecimalMark = num => num.toLocaleString('en-US'); // toDecimalMark(12305030388.9087) -> "12,305,030,388.9087" ``` diff --git a/snippets/toEnglishDate.md b/snippets/toEnglishDate.md index 329eea38b..ffbcf6cd7 100644 --- a/snippets/toEnglishDate.md +++ b/snippets/toEnglishDate.md @@ -6,7 +6,6 @@ Use `Date.toISOString()`, `split('T')` and `replace()` to convert a date from Am 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}}; +const toEnglishDate = (time) => { try { return new Date(time).toISOString().split('T')[0].replace(/-/g, '/'); } catch (e) {} }; // toEnglishDate('09/21/2010') -> '21/09/2010' ``` diff --git a/snippets/toSnakeCase.md b/snippets/toSnakeCase.md index fc9ae543a..b4022f98d 100644 --- a/snippets/toSnakeCase.md +++ b/snippets/toSnakeCase.md @@ -6,11 +6,11 @@ Break the string into words and combine them using `_` as a separator. For more detailed explanation of this Regex, [visit this Site](https://regex101.com/r/bMCgAB/1). ```js -const toSnakeCase = str =>{ +const toSnakeCase = str => { str && str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g) .map(x => x.toLowerCase()) .join('_'); -} +}; // toSnakeCase("camelCase") -> 'camel_case' // toSnakeCase("some text") -> 'some_text' // toSnakeCase("some-javascript-property") -> 'some_javascript_property' diff --git a/snippets/zip.md b/snippets/zip.md index c9a720e8e..981143fd5 100644 --- a/snippets/zip.md +++ b/snippets/zip.md @@ -10,9 +10,9 @@ If lengths of the argument-arrays vary, `undefined` is used where no value could const zip = (...arrays) => { const maxLength = Math.max(...arrays.map(x => x.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]] + 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/zipObject.md b/snippets/zipObject.md index f9214e7aa..be9172542 100644 --- a/snippets/zipObject.md +++ b/snippets/zipObject.md @@ -5,7 +5,7 @@ Given an array of valid property identifiers and an array of values, return an o Since an object can have undefined values but not undefined property pointers, the array of properties is used to decide the structure of the resulting object using `Array.reduce()`. ```js -const zipObject = ( props, values ) => props.reduce( ( obj, prop, index ) => ( obj[prop] = values[index], obj ), {} ) +const zipObject = (props, values) => props.reduce((obj, prop, index) => (obj[prop] = values[index], obj), {}); // zipObject(['a','b','c'], [1,2]) -> {a: 1, b: 2, c: undefined} // zipObject(['a','b'], [1,2,3]) -> {a: 1, b: 2} ```