diff --git a/README.md b/README.md index dee253d4a..4c8aa9c5a 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,7 @@ const anagrams = s => { return a; }, []); } +// anagrams('abc') -> ['abc','acb','bac','bca','cab','cba'] ``` ### Average of array of numbers @@ -75,6 +76,7 @@ Use `reduce()` to add each value to an accumulator, initialized with a value of ```js const average = arr => arr.reduce( (acc , val) => acc + val, 0) / arr.length; +// average([1,2,3]) -> 2 ``` ### Capitalize first letter of every word @@ -83,6 +85,7 @@ Use `replace()` to match the first character of each word and `toUpperCase()` to ```js const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase()); +// capitalizeEveryWord('hello world!') -> 'Hello World!' ``` ### Capitalize first letter @@ -93,6 +96,7 @@ Omit the `lowerRest` parameter to keep the rest of the string intact, or set it ```js const capitalize = (str, lowerRest = false) => str.slice(0, 1).toUpperCase() + (lowerRest? str.slice(1).toLowerCase() : str.slice(1)); +// capitalize('myName', true) -> 'Myname' ``` ### Check for palindrome @@ -101,7 +105,8 @@ Convert string `toLowerCase()` and use `replace()` to remove non-alphanumeric ch Then, `split('')` into individual characters, `reverse()`, `join('')` and compare to the original, unreversed string, after converting it `tolowerCase()`. ```js -const palindrome = str => (str.toLowerCase().replace(/[\W_]/g,'').split('').reverse().join('')==str.toLowerCase().replace(/[\W_]/g,'')); +const palindrome = str => (str.toLowerCase().replace(/[\W_]/g,'').split('').reverse().join('') === str.toLowerCase().replace(/[\W_]/g,'')); +// palindrome('taco cat') -> true ``` ### Count occurrences of a value in array @@ -110,6 +115,7 @@ Use `reduce()` to increment a counter each time you encounter the specific value ```js const countOccurrences = (arr, value) => arr.reduce((a, v) => v===value ? a + 1 : a + 0, 0); +// countOccurrences([1,1,2,1,2,3], 1) -> 3 ``` ### Current URL @@ -118,6 +124,7 @@ Use `window.location.href` to get current URL. ```js const currentUrl = _ => window.location.href; +// currentUrl() -> 'https://google.com' ``` ### Curry @@ -129,7 +136,8 @@ Otherwise return a curried function `f` that expects the rest of the arguments. ```js const curry = f => (...args) => - args.length >= f.length ? f(...args) : (...otherArgs) => curry(f)(...args, ...otherArgs) + args.length >= f.length ? f(...args) : (...otherArgs) => curry(f)(...args, ...otherArgs); +// curry(Math.pow)(2)(10) -> 1024 ``` ### Difference between arrays @@ -138,6 +146,7 @@ Use `filter()` to remove values that are part of `values`, determined using `inc ```js const difference = (arr, values) => arr.filter(v => !values.includes(v)); +// difference([1,2,3], [1,2]) -> [3] ``` ### Distance between two points @@ -146,6 +155,7 @@ Use `Math.hypot()` to calculate the Euclidean distance between two points. ```js const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0); +// distance(1,1, 2,3) -> 2.23606797749979 ``` ### Divisible by number @@ -154,6 +164,7 @@ Use the modulo operator (`%`) to check if the remainder is equal to `0`. ```js const isDivisible = (dividend, divisor) => dividend % divisor === 0; +// isDivisible(6,3) -> true ``` ### Escape regular expression @@ -163,7 +174,7 @@ Use `replace()` to escape special characters. ```js const escapeRegExp = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); -} +// escapeRegExp('(test)') -> \\(test\\) ``` ### Even or odd number @@ -173,6 +184,7 @@ Return `true` if the number is even, `false` if the number is odd. ```js const isEven = num => Math.abs(num) % 2 === 0; +// isEven(3) -> false ``` ### Factorial @@ -182,7 +194,8 @@ If `n` is less than or equal to `1`, return `1`. Otherwise, return the product of `n` and the factorial of `n - 1`. ```js -const factorial = n => n <= 1 ? 1 : n * factorial(n - 1) +const factorial = n => n <= 1 ? 1 : n * factorial(n - 1); +// factorial(6) -> 720 ``` ### Fibonacci array generator @@ -197,6 +210,7 @@ const fibonacci = n => acc.push( i>1 ? acc[i-1]+acc[i-2] : val); return acc; },[]); +// fibonacci(5) -> [0,1,1,2,3] ``` ### Filter out non-unique values in an array @@ -216,6 +230,7 @@ Use `reduce()` to get all elements that are not arrays, flatten each element tha ```js const flatten = arr => arr.reduce( (a, v) => a.concat( Array.isArray(v) ? flatten(v) : v ), []); +// flatten([1,[2],[[3],4],5]) -> [1,2,3,4,5] ``` ## Get scroll position @@ -238,6 +253,7 @@ Otherwise, return the GCD of `y` and the remainder of the division `x/y`. ```js const gcd = (x , y) => !y ? x : gcd(y, x % y); +// gcd (8, 36) -> 4 ``` ### Head of list @@ -246,6 +262,7 @@ Return `arr[0]`. ```js const head = arr => arr[0]; +// head([1,2,3]) -> 1 ``` ### Initial of list @@ -254,6 +271,7 @@ Return `arr.slice(0,-1)`. ```js const initial = arr => arr.slice(0,-1); +// initial([1,2,3]) -> [1,2] ``` ### Initialize array with range @@ -264,6 +282,7 @@ You can omit `start` to use a default value of `0`. ```js const initializeArrayRange = (end, start = 0) => Array.apply(null, Array(end-start)).map( (v,i) => i + start ); +// initializeArrayRange(5) -> [0,1,2,3,4] ``` ### Initialize array with values @@ -272,8 +291,8 @@ Use `Array(n)` to create an array of the desired length, `fill(v)` to fill it wi You can omit `v` to use a default value of `0`. ```js -const initializeArray = (n, v = 0) => - Array(n).fill(v); +const initializeArray = (n, v = 0) => Array(n).fill(v); +// initializeArray(5, 2) -> [2,2,2,2,2] ``` ### Last of list @@ -282,6 +301,7 @@ Return `arr.slice(-1)[0]`. ```js const last = arr => arr.slice(-1)[0]; +// last([1,2,3]) -> 3 ``` ### Measure time taken by function @@ -295,6 +315,7 @@ const timeTaken = (f,...args) => { console.log(performance.now() - t0); return r; } +// timeTaken(Math.pow, 2, 10) -> 1024 (0.010000000009313226 logged in console) ``` ### Object from key-value pairs @@ -302,7 +323,8 @@ const timeTaken = (f,...args) => { Use `Array.reduce()` to create and combine key-value pairs. ```js -const objectFromPairs = arr => arr => arr.reduce((a,b) => (a[b[0]] = b[1], a), {}); +const objectFromPairs = arr => arr.reduce((a,b) => (a[b[0]] = b[1], a), {}); +// objectFromPairs([['a',1],['b',2]]) -> {a: 1, b: 2} ``` ### Powerset @@ -312,6 +334,7 @@ Use `reduce()` combined with `map()` to iterate over elements and combine into a ```js const powerset = arr => arr.reduce( (a,v) => a.concat(a.map( r => [v].concat(r) )), [[]]); +// powerset([1,2]) -> [[], [1], [2], [2,1]] ``` ### Random number in range @@ -320,6 +343,7 @@ Use `Math.random()` to generate a random value, map it to the desired range usin ```js const randomInRange = (min, max) => Math.random() * (max - min) + min; +// randomInRange(2,10) -> 6.0211363285087005 ``` ### Randomize order of array @@ -327,7 +351,8 @@ const randomInRange = (min, max) => Math.random() * (max - min) + min; Use `sort()` to reorder elements, utilizing `Math.random()` to randomize the sorting. ```js -const randomizeOrder = arr => arr.sort( (a,b) => Math.random() >= 0.5 ? -1 : 1) +const randomizeOrder = arr => arr.sort( (a,b) => Math.random() >= 0.5 ? -1 : 1); +// randomizeOrder([1,2,3]) -> [1,3,2] ``` ### Redirect to URL @@ -338,6 +363,7 @@ Pass a second argument to simulate a link click (`true` - default) or an HTTP re ```js const redirect = (url, asLink = true) => asLink ? window.location.href = url : window.location.replace(url); +// redirect('https://google.com') ``` ### Reverse a string @@ -347,6 +373,7 @@ Combine characters to get a string using `join('')`. ```js const reverseString = str => [...str].reverse().join(''); +// reverseString('foobar') -> 'raboof' ``` ### RGB to hexadecimal @@ -357,6 +384,7 @@ Combine values using `join('')`. ```js const rgbToHex = (r, g, b) => [r,g,b].map( v => v.toString(16).padStart(2,'0')).join(''); +// rgbToHex(0, 127, 255) -> '007fff' ``` ### Scroll to top @@ -372,6 +400,7 @@ const scrollToTop = _ => { window.scrollTo(0, c - c/8); } } +// scrollToTop() ``` ### Similarity between arrays @@ -379,7 +408,8 @@ const scrollToTop = _ => { Use `filter()` to remove values that are not part of `values`, determined using `includes()`. ```js -const difference = (arr, values) => arr.filter(v => values.includes(v)); +const similarity = (arr, values) => arr.filter(v => values.includes(v)); +// similarity([1,2,3], [1,2,4]) -> [1,2] ``` ### Sort characters in string (alphabetical) @@ -389,6 +419,7 @@ Split the string using `split('')`, `sort()` utilizing `localeCompare()`, recomb ```js const sortCharactersInString = str => str.split('').sort( (a,b) => a.localeCompare(b) ).join(''); +// sortCharactersInString('cabbage') -> 'aabbceg' ``` ### Sum of array of numbers @@ -398,6 +429,7 @@ Use `reduce()` to add each value to an accumulator, initialized with a value of ```js const sum = arr => arr.reduce( (acc , val) => acc + val, 0); +// sum([1,2,3,4]) -> 10 ``` ### Swap values of two variables @@ -406,6 +438,7 @@ Use array destructuring to swap values between two variables. ```js [varA, varB] = [varB, varA]; +// [x, y] = [y, x] ``` ### Tail of list @@ -414,6 +447,7 @@ Return `arr.slice(1)`. ```js const tail = arr => arr.slice(1); +// tail([1,2,3]) -> [2,3] ``` ### Unique values of array @@ -434,6 +468,7 @@ Pass `location.search` as the argument to apply to the current `url`. ```js const getUrlParameters = url => Object.assign(...url.match(/([^?=&]+)(=([^&]*))?/g).map(m => {[f,v] = m.split('='); return {[f]:v}})); +// getUrlParameters('http://url.com/page?name=Adam&surname=Smith') -> {name: 'Adam', surname: 'Smith'} ``` ### UUID generator @@ -444,7 +479,8 @@ Use `crypto` API to generate a UUID, compliant with [RFC4122](https://www.ietf.o const uuid = _ => ( [1e7]+-1e3+-4e3+-8e3+-1e11 ).replace( /[018]/g, c => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16) - ) + ); +// uuid() -> '7982fcfe-5721-4632-bede-6000885be57d' ``` ### Validate number @@ -454,6 +490,7 @@ Use `isFinite()` to check if the number is finite. ```js const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n); +// validateNumber('10') -> true ``` ## Credits diff --git a/snippets/Check_for_palindrome.md b/snippets/Check_for_palindrome.md index 14268153d..b3f169eca 100644 --- a/snippets/Check_for_palindrome.md +++ b/snippets/Check_for_palindrome.md @@ -4,5 +4,6 @@ Convert string `toLowerCase()` and use `replace()` to remove non-alphanumeric ch Then, `split('')` into individual characters, `reverse()`, `join('')` and compare to the original, unreversed string, after converting it `tolowerCase()`. ```js -const palindrome = str => (str.toLowerCase().replace(/[\W_]/g,'').split('').reverse().join('')==str.toLowerCase().replace(/[\W_]/g,'')); +const palindrome = str => (str.toLowerCase().replace(/[\W_]/g,'').split('').reverse().join('') === str.toLowerCase().replace(/[\W_]/g,'')); +// palindrome('taco cat') -> true ``` diff --git a/snippets/RGB-to-hexadecimal.md b/snippets/RGB-to-hexadecimal.md index 102821d53..c40fa2ff4 100644 --- a/snippets/RGB-to-hexadecimal.md +++ b/snippets/RGB-to-hexadecimal.md @@ -6,4 +6,5 @@ Combine values using `join('')`. ```js const rgbToHex = (r, g, b) => [r,g,b].map( v => v.toString(16).padStart(2,'0')).join(''); +// rgbToHex(0, 127, 255) -> '007fff' ``` diff --git a/snippets/URL-parameters.md b/snippets/URL-parameters.md index 9c1aff9a4..4620513dc 100644 --- a/snippets/URL-parameters.md +++ b/snippets/URL-parameters.md @@ -7,4 +7,5 @@ Pass `location.search` as the argument to apply to the current `url`. ```js const getUrlParameters = url => Object.assign(...url.match(/([^?=&]+)(=([^&]*))?/g).map(m => {[f,v] = m.split('='); return {[f]:v}})); +// getUrlParameters('http://url.com/page?name=Adam&surname=Smith') -> {name: 'Adam', surname: 'Smith'} ``` diff --git a/snippets/UUID-generator.md b/snippets/UUID-generator.md index 1dafab3a1..b7860cf64 100644 --- a/snippets/UUID-generator.md +++ b/snippets/UUID-generator.md @@ -6,5 +6,6 @@ Use `crypto` API to generate a UUID, compliant with [RFC4122](https://www.ietf.o const uuid = _ => ( [1e7]+-1e3+-4e3+-8e3+-1e11 ).replace( /[018]/g, c => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16) - ) + ); +// uuid() -> '7982fcfe-5721-4632-bede-6000885be57d' ``` diff --git a/snippets/anagrams-of-string-(with-duplicates).md b/snippets/anagrams-of-string-(with-duplicates).md index 97140f0e4..baacecf49 100644 --- a/snippets/anagrams-of-string-(with-duplicates).md +++ b/snippets/anagrams-of-string-(with-duplicates).md @@ -13,4 +13,5 @@ const anagrams = s => { return a; }, []); } +// anagrams('abc') -> ['abc','acb','bac','bca','cab','cba'] ``` diff --git a/snippets/average-of-array-of-numbers.md b/snippets/average-of-array-of-numbers.md index 53119bc32..615e183b8 100644 --- a/snippets/average-of-array-of-numbers.md +++ b/snippets/average-of-array-of-numbers.md @@ -5,4 +5,5 @@ Use `reduce()` to add each value to an accumulator, initialized with a value of ```js const average = arr => arr.reduce( (acc , val) => acc + val, 0) / arr.length; +// average([1,2,3]) -> 2 ``` diff --git a/snippets/capitalize-first-letter-of-every-word.md b/snippets/capitalize-first-letter-of-every-word.md index 6c93eecd4..4a1f5c1ab 100644 --- a/snippets/capitalize-first-letter-of-every-word.md +++ b/snippets/capitalize-first-letter-of-every-word.md @@ -4,4 +4,5 @@ Use `replace()` to match the first character of each word and `toUpperCase()` to ```js const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase()); +// capitalizeEveryWord('hello world!') -> 'Hello World!' ``` diff --git a/snippets/capitalize-first-letter.md b/snippets/capitalize-first-letter.md index f6b933998..99be77927 100644 --- a/snippets/capitalize-first-letter.md +++ b/snippets/capitalize-first-letter.md @@ -6,4 +6,5 @@ Omit the `lowerRest` parameter to keep the rest of the string intact, or set it ```js const capitalize = (str, lowerRest = false) => str.slice(0, 1).toUpperCase() + (lowerRest? str.slice(1).toLowerCase() : str.slice(1)); +// capitalize('myName', true) -> 'Myname' ``` diff --git a/snippets/count-occurrences-of-a-value-in-array.md b/snippets/count-occurrences-of-a-value-in-array.md index 459aa08d3..552ad9f39 100644 --- a/snippets/count-occurrences-of-a-value-in-array.md +++ b/snippets/count-occurrences-of-a-value-in-array.md @@ -4,4 +4,5 @@ Use `reduce()` to increment a counter each time you encounter the specific value ```js const countOccurrences = (arr, value) => arr.reduce((a, v) => v===value ? a + 1 : a + 0, 0); +// countOccurrences([1,1,2,1,2,3], 1) -> 3 ``` diff --git a/snippets/current-URL.md b/snippets/current-URL.md index 6256aeaea..200cf150b 100644 --- a/snippets/current-URL.md +++ b/snippets/current-URL.md @@ -4,4 +4,5 @@ Use `window.location.href` to get current URL. ```js const currentUrl = _ => window.location.href; +// currentUrl() -> 'https://google.com' ``` diff --git a/snippets/curry.md b/snippets/curry.md index b03d6bf3e..a700ac776 100644 --- a/snippets/curry.md +++ b/snippets/curry.md @@ -7,5 +7,6 @@ Otherwise return a curried function `f` that expects the rest of the arguments. ```js const curry = f => (...args) => - args.length >= f.length ? f(...args) : (...otherArgs) => curry(f)(...args, ...otherArgs) + args.length >= f.length ? f(...args) : (...otherArgs) => curry(f)(...args, ...otherArgs); +// curry(Math.pow)(2)(10) -> 1024 ``` diff --git a/snippets/difference-between-arrays.md b/snippets/difference-between-arrays.md index 9976f67a9..1fb172dab 100644 --- a/snippets/difference-between-arrays.md +++ b/snippets/difference-between-arrays.md @@ -4,4 +4,5 @@ Use `filter()` to remove values that are part of `values`, determined using `inc ```js const difference = (arr, values) => arr.filter(v => !values.includes(v)); +// difference([1,2,3], [1,2]) -> [3] ``` diff --git a/snippets/distance-between-two-points.md b/snippets/distance-between-two-points.md index a93ca2102..33eea1615 100644 --- a/snippets/distance-between-two-points.md +++ b/snippets/distance-between-two-points.md @@ -4,4 +4,5 @@ Use `Math.hypot()` to calculate the Euclidean distance between two points. ```js const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0); +// distance(1,1, 2,3) -> 2.23606797749979 ``` diff --git a/snippets/divisible-by-number.md b/snippets/divisible-by-number.md index 7f608f12d..8bc182fed 100644 --- a/snippets/divisible-by-number.md +++ b/snippets/divisible-by-number.md @@ -4,4 +4,5 @@ Use the modulo operator (`%`) to check if the remainder is equal to `0`. ```js const isDivisible = (dividend, divisor) => dividend % divisor === 0; +// isDivisible(6,3) -> true ``` diff --git a/snippets/escape-regular-expression.md b/snippets/escape-regular-expression.md index 69fd9958a..4bd77a0d9 100644 --- a/snippets/escape-regular-expression.md +++ b/snippets/escape-regular-expression.md @@ -5,5 +5,5 @@ Use `replace()` to escape special characters. ```js const escapeRegExp = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); -} +// escapeRegExp('(test)') -> \\(test\\) ``` diff --git a/snippets/even-or-odd-number.md b/snippets/even-or-odd-number.md index c846aa517..605108429 100644 --- a/snippets/even-or-odd-number.md +++ b/snippets/even-or-odd-number.md @@ -5,4 +5,5 @@ Return `true` if the number is even, `false` if the number is odd. ```js const isEven = num => Math.abs(num) % 2 === 0; +// isEven(3) -> false ``` diff --git a/snippets/factorial.md b/snippets/factorial.md index 8472c3f51..155b7229e 100644 --- a/snippets/factorial.md +++ b/snippets/factorial.md @@ -5,5 +5,6 @@ If `n` is less than or equal to `1`, return `1`. Otherwise, return the product of `n` and the factorial of `n - 1`. ```js -const factorial = n => n <= 1 ? 1 : n * factorial(n - 1) +const factorial = n => n <= 1 ? 1 : n * factorial(n - 1); +// factorial(6) -> 720 ``` diff --git a/snippets/fibonacci-array-generator.md b/snippets/fibonacci-array-generator.md index 08a587565..ef6a2a975 100644 --- a/snippets/fibonacci-array-generator.md +++ b/snippets/fibonacci-array-generator.md @@ -10,4 +10,5 @@ const fibonacci = n => acc.push( i>1 ? acc[i-1]+acc[i-2] : val); return acc; },[]); +// fibonacci(5) -> [0,1,1,2,3] ``` diff --git a/snippets/flatten-array.md b/snippets/flatten-array.md index cba163a5e..f3b1c9f4b 100644 --- a/snippets/flatten-array.md +++ b/snippets/flatten-array.md @@ -6,4 +6,5 @@ Use `reduce()` to get all elements that are not arrays, flatten each element tha ```js const flatten = arr => arr.reduce( (a, v) => a.concat( Array.isArray(v) ? flatten(v) : v ), []); +// flatten([1,[2],[[3],4],5]) -> [1,2,3,4,5] ``` diff --git a/snippets/greatest-common-divisor-(GCD).md b/snippets/greatest-common-divisor-(GCD).md index 32935afe7..38b5603ca 100644 --- a/snippets/greatest-common-divisor-(GCD).md +++ b/snippets/greatest-common-divisor-(GCD).md @@ -6,4 +6,5 @@ Otherwise, return the GCD of `y` and the remainder of the division `x/y`. ```js const gcd = (x , y) => !y ? x : gcd(y, x % y); +// gcd (8, 36) -> 4 ``` diff --git a/snippets/head-of-list.md b/snippets/head-of-list.md index 16aec6a09..31dc5fbaf 100644 --- a/snippets/head-of-list.md +++ b/snippets/head-of-list.md @@ -4,4 +4,5 @@ Return `arr[0]`. ```js const head = arr => arr[0]; +// head([1,2,3]) -> 1 ``` diff --git a/snippets/initial-of-list.md b/snippets/initial-of-list.md index 273c6d737..77ea3e8f7 100644 --- a/snippets/initial-of-list.md +++ b/snippets/initial-of-list.md @@ -4,4 +4,5 @@ Return `arr.slice(0,-1)`. ```js const initial = arr => arr.slice(0,-1); +// initial([1,2,3]) -> [1,2] ``` diff --git a/snippets/initialize-array-with-range.md b/snippets/initialize-array-with-range.md index cdcc8fb82..c974f2786 100644 --- a/snippets/initialize-array-with-range.md +++ b/snippets/initialize-array-with-range.md @@ -6,4 +6,5 @@ You can omit `start` to use a default value of `0`. ```js const initializeArrayRange = (end, start = 0) => Array.apply(null, Array(end-start)).map( (v,i) => i + start ); +// initializeArrayRange(5) -> [0,1,2,3,4] ``` diff --git a/snippets/initialize-array-with-values.md b/snippets/initialize-array-with-values.md index a01104ea8..3ee75f97c 100644 --- a/snippets/initialize-array-with-values.md +++ b/snippets/initialize-array-with-values.md @@ -4,6 +4,6 @@ Use `Array(n)` to create an array of the desired length, `fill(v)` to fill it wi You can omit `v` to use a default value of `0`. ```js -const initializeArray = (n, v = 0) => - Array(n).fill(v); +const initializeArray = (n, v = 0) => Array(n).fill(v); +// initializeArray(5, 2) -> [2,2,2,2,2] ``` diff --git a/snippets/last-of-list.md b/snippets/last-of-list.md index 62f7219a7..16955f201 100644 --- a/snippets/last-of-list.md +++ b/snippets/last-of-list.md @@ -4,4 +4,5 @@ Return `arr.slice(-1)[0]`. ```js const last = arr => arr.slice(-1)[0]; +// last([1,2,3]) -> 3 ``` diff --git a/snippets/measure-time-taken-by-function.md b/snippets/measure-time-taken-by-function.md index 88dc7d48a..5f39c34ed 100644 --- a/snippets/measure-time-taken-by-function.md +++ b/snippets/measure-time-taken-by-function.md @@ -9,4 +9,5 @@ const timeTaken = (f,...args) => { console.log(performance.now() - t0); return r; } +// timeTaken(Math.pow, 2, 10) -> 1024 (0.010000000009313226 logged in console) ``` diff --git a/snippets/object-from-key-value-pairs.md b/snippets/object-from-key-value-pairs.md index 90f41802c..0f7a60e44 100644 --- a/snippets/object-from-key-value-pairs.md +++ b/snippets/object-from-key-value-pairs.md @@ -3,5 +3,6 @@ Use `Array.reduce()` to create and combine key-value pairs. ```js -const objectFromPairs = arr => arr => arr.reduce((a,b) => (a[b[0]] = b[1], a), {}); +const objectFromPairs = arr => arr.reduce((a,b) => (a[b[0]] = b[1], a), {}); +// objectFromPairs([['a',1],['b',2]]) -> {a: 1, b: 2} ``` diff --git a/snippets/powerset.md b/snippets/powerset.md index de2ecdc42..2908c78b2 100644 --- a/snippets/powerset.md +++ b/snippets/powerset.md @@ -5,4 +5,5 @@ Use `reduce()` combined with `map()` to iterate over elements and combine into a ```js const powerset = arr => arr.reduce( (a,v) => a.concat(a.map( r => [v].concat(r) )), [[]]); +// powerset([1,2]) -> [[], [1], [2], [2,1]] ``` diff --git a/snippets/random-number-in-range.md b/snippets/random-number-in-range.md index ed4dc7af8..f2592b78e 100644 --- a/snippets/random-number-in-range.md +++ b/snippets/random-number-in-range.md @@ -4,4 +4,5 @@ Use `Math.random()` to generate a random value, map it to the desired range usin ```js const randomInRange = (min, max) => Math.random() * (max - min) + min; +// randomInRange(2,10) -> 6.0211363285087005 ``` diff --git a/snippets/randomize-order-of-array.md b/snippets/randomize-order-of-array.md index ed826338d..fe9093843 100644 --- a/snippets/randomize-order-of-array.md +++ b/snippets/randomize-order-of-array.md @@ -3,5 +3,6 @@ Use `sort()` to reorder elements, utilizing `Math.random()` to randomize the sorting. ```js -const randomizeOrder = arr => arr.sort( (a,b) => Math.random() >= 0.5 ? -1 : 1) +const randomizeOrder = arr => arr.sort( (a,b) => Math.random() >= 0.5 ? -1 : 1); +// randomizeOrder([1,2,3]) -> [1,3,2] ``` diff --git a/snippets/redirect-to-url.md b/snippets/redirect-to-url.md index e459c9ea7..dab1f775b 100644 --- a/snippets/redirect-to-url.md +++ b/snippets/redirect-to-url.md @@ -6,4 +6,5 @@ Pass a second argument to simulate a link click (`true` - default) or an HTTP re ```js const redirect = (url, asLink = true) => asLink ? window.location.href = url : window.location.replace(url); +// redirect('https://google.com') ``` diff --git a/snippets/reverse-a-string.md b/snippets/reverse-a-string.md index a8612177e..172eab6b6 100644 --- a/snippets/reverse-a-string.md +++ b/snippets/reverse-a-string.md @@ -5,4 +5,5 @@ Combine characters to get a string using `join('')`. ```js const reverseString = str => [...str].reverse().join(''); +// reverseString('foobar') -> 'raboof' ``` diff --git a/snippets/scroll-to-top.md b/snippets/scroll-to-top.md index 1765fb4f3..7a813429a 100644 --- a/snippets/scroll-to-top.md +++ b/snippets/scroll-to-top.md @@ -11,4 +11,5 @@ const scrollToTop = _ => { window.scrollTo(0, c - c/8); } } +// scrollToTop() ``` diff --git a/snippets/similarity-between-arrays.md b/snippets/similarity-between-arrays.md index 7b71c56bd..44f19b7bb 100644 --- a/snippets/similarity-between-arrays.md +++ b/snippets/similarity-between-arrays.md @@ -3,5 +3,6 @@ Use `filter()` to remove values that are not part of `values`, determined using `includes()`. ```js -const difference = (arr, values) => arr.filter(v => values.includes(v)); +const similarity = (arr, values) => arr.filter(v => values.includes(v)); +// similarity([1,2,3], [1,2,4]) -> [1,2] ``` diff --git a/snippets/sort-characters-in-string-(alphabetical).md b/snippets/sort-characters-in-string-(alphabetical).md index ac3c8208b..c283ca17c 100644 --- a/snippets/sort-characters-in-string-(alphabetical).md +++ b/snippets/sort-characters-in-string-(alphabetical).md @@ -5,4 +5,5 @@ Split the string using `split('')`, `sort()` utilizing `localeCompare()`, recomb ```js const sortCharactersInString = str => str.split('').sort( (a,b) => a.localeCompare(b) ).join(''); +// sortCharactersInString('cabbage') -> 'aabbceg' ``` diff --git a/snippets/sum-of-array-of-numbers.md b/snippets/sum-of-array-of-numbers.md index e5207ccb0..f2805b08f 100644 --- a/snippets/sum-of-array-of-numbers.md +++ b/snippets/sum-of-array-of-numbers.md @@ -5,4 +5,5 @@ Use `reduce()` to add each value to an accumulator, initialized with a value of ```js const sum = arr => arr.reduce( (acc , val) => acc + val, 0); +// sum([1,2,3,4]) -> 10 ``` diff --git a/snippets/swap-values-of-two-variables.md b/snippets/swap-values-of-two-variables.md index d1cd017b9..bb2f67150 100644 --- a/snippets/swap-values-of-two-variables.md +++ b/snippets/swap-values-of-two-variables.md @@ -4,4 +4,5 @@ Use array destructuring to swap values between two variables. ```js [varA, varB] = [varB, varA]; +// [x, y] = [y, x] ``` diff --git a/snippets/tail-of-list.md b/snippets/tail-of-list.md index 802a91ec6..9a9513262 100644 --- a/snippets/tail-of-list.md +++ b/snippets/tail-of-list.md @@ -4,4 +4,5 @@ Return `arr.slice(1)`. ```js const tail = arr => arr.slice(1); +// tail([1,2,3]) -> [2,3] ``` diff --git a/snippets/validate-number.md b/snippets/validate-number.md index 6f273350d..a26eca627 100644 --- a/snippets/validate-number.md +++ b/snippets/validate-number.md @@ -5,4 +5,5 @@ Use `isFinite()` to check if the number is finite. ```js const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n); +// validateNumber('10') -> true ```