Added samples

This commit is contained in:
Angelos Chalaris
2017-12-12 17:50:08 +02:00
parent e93e618283
commit 43f8529cb9
40 changed files with 94 additions and 20 deletions

View File

@ -66,6 +66,7 @@ const anagrams = s => {
return a; return a;
}, []); }, []);
} }
// anagrams('abc') -> ['abc','acb','bac','bca','cab','cba']
``` ```
### Average of array of numbers ### Average of array of numbers
@ -75,6 +76,7 @@ Use `reduce()` to add each value to an accumulator, initialized with a value of
```js ```js
const average = arr => const average = arr =>
arr.reduce( (acc , val) => acc + val, 0) / arr.length; arr.reduce( (acc , val) => acc + val, 0) / arr.length;
// average([1,2,3]) -> 2
``` ```
### Capitalize first letter of every word ### Capitalize first letter of every word
@ -83,6 +85,7 @@ Use `replace()` to match the first character of each word and `toUpperCase()` to
```js ```js
const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase()); const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
// capitalizeEveryWord('hello world!') -> 'Hello World!'
``` ```
### Capitalize first letter ### Capitalize first letter
@ -93,6 +96,7 @@ Omit the `lowerRest` parameter to keep the rest of the string intact, or set it
```js ```js
const capitalize = (str, lowerRest = false) => const capitalize = (str, lowerRest = false) =>
str.slice(0, 1).toUpperCase() + (lowerRest? str.slice(1).toLowerCase() : str.slice(1)); str.slice(0, 1).toUpperCase() + (lowerRest? str.slice(1).toLowerCase() : str.slice(1));
// capitalize('myName', true) -> 'Myname'
``` ```
### Check for palindrome ### 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()`. Then, `split('')` into individual characters, `reverse()`, `join('')` and compare to the original, unreversed string, after converting it `tolowerCase()`.
```js ```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 ### 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 ```js
const countOccurrences = (arr, value) => arr.reduce((a, v) => v===value ? a + 1 : a + 0, 0); 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 ### Current URL
@ -118,6 +124,7 @@ Use `window.location.href` to get current URL.
```js ```js
const currentUrl = _ => window.location.href; const currentUrl = _ => window.location.href;
// currentUrl() -> 'https://google.com'
``` ```
### Curry ### Curry
@ -129,7 +136,8 @@ Otherwise return a curried function `f` that expects the rest of the arguments.
```js ```js
const curry = f => const curry = f =>
(...args) => (...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 ### Difference between arrays
@ -138,6 +146,7 @@ Use `filter()` to remove values that are part of `values`, determined using `inc
```js ```js
const difference = (arr, values) => arr.filter(v => !values.includes(v)); const difference = (arr, values) => arr.filter(v => !values.includes(v));
// difference([1,2,3], [1,2]) -> [3]
``` ```
### Distance between two points ### Distance between two points
@ -146,6 +155,7 @@ Use `Math.hypot()` to calculate the Euclidean distance between two points.
```js ```js
const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0); const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
// distance(1,1, 2,3) -> 2.23606797749979
``` ```
### Divisible by number ### Divisible by number
@ -154,6 +164,7 @@ Use the modulo operator (`%`) to check if the remainder is equal to `0`.
```js ```js
const isDivisible = (dividend, divisor) => dividend % divisor === 0; const isDivisible = (dividend, divisor) => dividend % divisor === 0;
// isDivisible(6,3) -> true
``` ```
### Escape regular expression ### Escape regular expression
@ -163,7 +174,7 @@ Use `replace()` to escape special characters.
```js ```js
const escapeRegExp = s => const escapeRegExp = s =>
s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
} // escapeRegExp('(test)') -> \\(test\\)
``` ```
### Even or odd number ### Even or odd number
@ -173,6 +184,7 @@ Return `true` if the number is even, `false` if the number is odd.
```js ```js
const isEven = num => Math.abs(num) % 2 === 0; const isEven = num => Math.abs(num) % 2 === 0;
// isEven(3) -> false
``` ```
### Factorial ### 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`. Otherwise, return the product of `n` and the factorial of `n - 1`.
```js ```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 ### Fibonacci array generator
@ -197,6 +210,7 @@ const fibonacci = n =>
acc.push( i>1 ? acc[i-1]+acc[i-2] : val); acc.push( i>1 ? acc[i-1]+acc[i-2] : val);
return acc; return acc;
},[]); },[]);
// fibonacci(5) -> [0,1,1,2,3]
``` ```
### Filter out non-unique values in an array ### 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 ```js
const flatten = arr => const flatten = arr =>
arr.reduce( (a, v) => a.concat( Array.isArray(v) ? flatten(v) : v ), []); 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 ## Get scroll position
@ -238,6 +253,7 @@ Otherwise, return the GCD of `y` and the remainder of the division `x/y`.
```js ```js
const gcd = (x , y) => !y ? x : gcd(y, x % y); const gcd = (x , y) => !y ? x : gcd(y, x % y);
// gcd (8, 36) -> 4
``` ```
### Head of list ### Head of list
@ -246,6 +262,7 @@ Return `arr[0]`.
```js ```js
const head = arr => arr[0]; const head = arr => arr[0];
// head([1,2,3]) -> 1
``` ```
### Initial of list ### Initial of list
@ -254,6 +271,7 @@ Return `arr.slice(0,-1)`.
```js ```js
const initial = arr => arr.slice(0,-1); const initial = arr => arr.slice(0,-1);
// initial([1,2,3]) -> [1,2]
``` ```
### Initialize array with range ### Initialize array with range
@ -264,6 +282,7 @@ You can omit `start` to use a default value of `0`.
```js ```js
const initializeArrayRange = (end, start = 0) => const initializeArrayRange = (end, start = 0) =>
Array.apply(null, Array(end-start)).map( (v,i) => i + start ); Array.apply(null, Array(end-start)).map( (v,i) => i + start );
// initializeArrayRange(5) -> [0,1,2,3,4]
``` ```
### Initialize array with values ### 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`. You can omit `v` to use a default value of `0`.
```js ```js
const initializeArray = (n, v = 0) => const initializeArray = (n, v = 0) => Array(n).fill(v);
Array(n).fill(v); // initializeArray(5, 2) -> [2,2,2,2,2]
``` ```
### Last of list ### Last of list
@ -282,6 +301,7 @@ Return `arr.slice(-1)[0]`.
```js ```js
const last = arr => arr.slice(-1)[0]; const last = arr => arr.slice(-1)[0];
// last([1,2,3]) -> 3
``` ```
### Measure time taken by function ### Measure time taken by function
@ -295,6 +315,7 @@ const timeTaken = (f,...args) => {
console.log(performance.now() - t0); console.log(performance.now() - t0);
return r; return r;
} }
// timeTaken(Math.pow, 2, 10) -> 1024 (0.010000000009313226 logged in console)
``` ```
### Object from key-value pairs ### Object from key-value pairs
@ -302,7 +323,8 @@ const timeTaken = (f,...args) => {
Use `Array.reduce()` to create and combine key-value pairs. Use `Array.reduce()` to create and combine key-value pairs.
```js ```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 ### Powerset
@ -312,6 +334,7 @@ Use `reduce()` combined with `map()` to iterate over elements and combine into a
```js ```js
const powerset = arr => const powerset = arr =>
arr.reduce( (a,v) => a.concat(a.map( r => [v].concat(r) )), [[]]); arr.reduce( (a,v) => a.concat(a.map( r => [v].concat(r) )), [[]]);
// powerset([1,2]) -> [[], [1], [2], [2,1]]
``` ```
### Random number in range ### Random number in range
@ -320,6 +343,7 @@ Use `Math.random()` to generate a random value, map it to the desired range usin
```js ```js
const randomInRange = (min, max) => Math.random() * (max - min) + min; const randomInRange = (min, max) => Math.random() * (max - min) + min;
// randomInRange(2,10) -> 6.0211363285087005
``` ```
### Randomize order of array ### 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. Use `sort()` to reorder elements, utilizing `Math.random()` to randomize the sorting.
```js ```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 ### Redirect to URL
@ -338,6 +363,7 @@ Pass a second argument to simulate a link click (`true` - default) or an HTTP re
```js ```js
const redirect = (url, asLink = true) => const redirect = (url, asLink = true) =>
asLink ? window.location.href = url : window.location.replace(url); asLink ? window.location.href = url : window.location.replace(url);
// redirect('https://google.com')
``` ```
### Reverse a string ### Reverse a string
@ -347,6 +373,7 @@ Combine characters to get a string using `join('')`.
```js ```js
const reverseString = str => [...str].reverse().join(''); const reverseString = str => [...str].reverse().join('');
// reverseString('foobar') -> 'raboof'
``` ```
### RGB to hexadecimal ### RGB to hexadecimal
@ -357,6 +384,7 @@ Combine values using `join('')`.
```js ```js
const rgbToHex = (r, g, b) => const rgbToHex = (r, g, b) =>
[r,g,b].map( v => v.toString(16).padStart(2,'0')).join(''); [r,g,b].map( v => v.toString(16).padStart(2,'0')).join('');
// rgbToHex(0, 127, 255) -> '007fff'
``` ```
### Scroll to top ### Scroll to top
@ -372,6 +400,7 @@ const scrollToTop = _ => {
window.scrollTo(0, c - c/8); window.scrollTo(0, c - c/8);
} }
} }
// scrollToTop()
``` ```
### Similarity between arrays ### Similarity between arrays
@ -379,7 +408,8 @@ const scrollToTop = _ => {
Use `filter()` to remove values that are not part of `values`, determined using `includes()`. Use `filter()` to remove values that are not part of `values`, determined using `includes()`.
```js ```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) ### Sort characters in string (alphabetical)
@ -389,6 +419,7 @@ Split the string using `split('')`, `sort()` utilizing `localeCompare()`, recomb
```js ```js
const sortCharactersInString = str => const sortCharactersInString = str =>
str.split('').sort( (a,b) => a.localeCompare(b) ).join(''); str.split('').sort( (a,b) => a.localeCompare(b) ).join('');
// sortCharactersInString('cabbage') -> 'aabbceg'
``` ```
### Sum of array of numbers ### Sum of array of numbers
@ -398,6 +429,7 @@ Use `reduce()` to add each value to an accumulator, initialized with a value of
```js ```js
const sum = arr => const sum = arr =>
arr.reduce( (acc , val) => acc + val, 0); arr.reduce( (acc , val) => acc + val, 0);
// sum([1,2,3,4]) -> 10
``` ```
### Swap values of two variables ### Swap values of two variables
@ -406,6 +438,7 @@ Use array destructuring to swap values between two variables.
```js ```js
[varA, varB] = [varB, varA]; [varA, varB] = [varB, varA];
// [x, y] = [y, x]
``` ```
### Tail of list ### Tail of list
@ -414,6 +447,7 @@ Return `arr.slice(1)`.
```js ```js
const tail = arr => arr.slice(1); const tail = arr => arr.slice(1);
// tail([1,2,3]) -> [2,3]
``` ```
### Unique values of array ### Unique values of array
@ -434,6 +468,7 @@ Pass `location.search` as the argument to apply to the current `url`.
```js ```js
const getUrlParameters = url => const getUrlParameters = url =>
Object.assign(...url.match(/([^?=&]+)(=([^&]*))?/g).map(m => {[f,v] = m.split('='); return {[f]:v}})); 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 ### UUID generator
@ -444,7 +479,8 @@ Use `crypto` API to generate a UUID, compliant with [RFC4122](https://www.ietf.o
const uuid = _ => const uuid = _ =>
( [1e7]+-1e3+-4e3+-8e3+-1e11 ).replace( /[018]/g, c => ( [1e7]+-1e3+-4e3+-8e3+-1e11 ).replace( /[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16) (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
) );
// uuid() -> '7982fcfe-5721-4632-bede-6000885be57d'
``` ```
### Validate number ### Validate number
@ -454,6 +490,7 @@ Use `isFinite()` to check if the number is finite.
```js ```js
const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n); const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n);
// validateNumber('10') -> true
``` ```
## Credits ## Credits

View File

@ -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()`. Then, `split('')` into individual characters, `reverse()`, `join('')` and compare to the original, unreversed string, after converting it `tolowerCase()`.
```js ```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
``` ```

View File

@ -6,4 +6,5 @@ Combine values using `join('')`.
```js ```js
const rgbToHex = (r, g, b) => const rgbToHex = (r, g, b) =>
[r,g,b].map( v => v.toString(16).padStart(2,'0')).join(''); [r,g,b].map( v => v.toString(16).padStart(2,'0')).join('');
// rgbToHex(0, 127, 255) -> '007fff'
``` ```

View File

@ -7,4 +7,5 @@ Pass `location.search` as the argument to apply to the current `url`.
```js ```js
const getUrlParameters = url => const getUrlParameters = url =>
Object.assign(...url.match(/([^?=&]+)(=([^&]*))?/g).map(m => {[f,v] = m.split('='); return {[f]:v}})); 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'}
``` ```

View File

@ -6,5 +6,6 @@ Use `crypto` API to generate a UUID, compliant with [RFC4122](https://www.ietf.o
const uuid = _ => const uuid = _ =>
( [1e7]+-1e3+-4e3+-8e3+-1e11 ).replace( /[018]/g, c => ( [1e7]+-1e3+-4e3+-8e3+-1e11 ).replace( /[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16) (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
) );
// uuid() -> '7982fcfe-5721-4632-bede-6000885be57d'
``` ```

View File

@ -13,4 +13,5 @@ const anagrams = s => {
return a; return a;
}, []); }, []);
} }
// anagrams('abc') -> ['abc','acb','bac','bca','cab','cba']
``` ```

View File

@ -5,4 +5,5 @@ Use `reduce()` to add each value to an accumulator, initialized with a value of
```js ```js
const average = arr => const average = arr =>
arr.reduce( (acc , val) => acc + val, 0) / arr.length; arr.reduce( (acc , val) => acc + val, 0) / arr.length;
// average([1,2,3]) -> 2
``` ```

View File

@ -4,4 +4,5 @@ Use `replace()` to match the first character of each word and `toUpperCase()` to
```js ```js
const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase()); const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
// capitalizeEveryWord('hello world!') -> 'Hello World!'
``` ```

View File

@ -6,4 +6,5 @@ Omit the `lowerRest` parameter to keep the rest of the string intact, or set it
```js ```js
const capitalize = (str, lowerRest = false) => const capitalize = (str, lowerRest = false) =>
str.slice(0, 1).toUpperCase() + (lowerRest? str.slice(1).toLowerCase() : str.slice(1)); str.slice(0, 1).toUpperCase() + (lowerRest? str.slice(1).toLowerCase() : str.slice(1));
// capitalize('myName', true) -> 'Myname'
``` ```

View File

@ -4,4 +4,5 @@ Use `reduce()` to increment a counter each time you encounter the specific value
```js ```js
const countOccurrences = (arr, value) => arr.reduce((a, v) => v===value ? a + 1 : a + 0, 0); const countOccurrences = (arr, value) => arr.reduce((a, v) => v===value ? a + 1 : a + 0, 0);
// countOccurrences([1,1,2,1,2,3], 1) -> 3
``` ```

View File

@ -4,4 +4,5 @@ Use `window.location.href` to get current URL.
```js ```js
const currentUrl = _ => window.location.href; const currentUrl = _ => window.location.href;
// currentUrl() -> 'https://google.com'
``` ```

View File

@ -7,5 +7,6 @@ Otherwise return a curried function `f` that expects the rest of the arguments.
```js ```js
const curry = f => const curry = f =>
(...args) => (...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
``` ```

View File

@ -4,4 +4,5 @@ Use `filter()` to remove values that are part of `values`, determined using `inc
```js ```js
const difference = (arr, values) => arr.filter(v => !values.includes(v)); const difference = (arr, values) => arr.filter(v => !values.includes(v));
// difference([1,2,3], [1,2]) -> [3]
``` ```

View File

@ -4,4 +4,5 @@ Use `Math.hypot()` to calculate the Euclidean distance between two points.
```js ```js
const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0); const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
// distance(1,1, 2,3) -> 2.23606797749979
``` ```

View File

@ -4,4 +4,5 @@ Use the modulo operator (`%`) to check if the remainder is equal to `0`.
```js ```js
const isDivisible = (dividend, divisor) => dividend % divisor === 0; const isDivisible = (dividend, divisor) => dividend % divisor === 0;
// isDivisible(6,3) -> true
``` ```

View File

@ -5,5 +5,5 @@ Use `replace()` to escape special characters.
```js ```js
const escapeRegExp = s => const escapeRegExp = s =>
s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
} // escapeRegExp('(test)') -> \\(test\\)
``` ```

View File

@ -5,4 +5,5 @@ Return `true` if the number is even, `false` if the number is odd.
```js ```js
const isEven = num => Math.abs(num) % 2 === 0; const isEven = num => Math.abs(num) % 2 === 0;
// isEven(3) -> false
``` ```

View File

@ -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`. Otherwise, return the product of `n` and the factorial of `n - 1`.
```js ```js
const factorial = n => n <= 1 ? 1 : n * factorial(n - 1) const factorial = n => n <= 1 ? 1 : n * factorial(n - 1);
// factorial(6) -> 720
``` ```

View File

@ -10,4 +10,5 @@ const fibonacci = n =>
acc.push( i>1 ? acc[i-1]+acc[i-2] : val); acc.push( i>1 ? acc[i-1]+acc[i-2] : val);
return acc; return acc;
},[]); },[]);
// fibonacci(5) -> [0,1,1,2,3]
``` ```

View File

@ -6,4 +6,5 @@ Use `reduce()` to get all elements that are not arrays, flatten each element tha
```js ```js
const flatten = arr => const flatten = arr =>
arr.reduce( (a, v) => a.concat( Array.isArray(v) ? flatten(v) : v ), []); arr.reduce( (a, v) => a.concat( Array.isArray(v) ? flatten(v) : v ), []);
// flatten([1,[2],[[3],4],5]) -> [1,2,3,4,5]
``` ```

View File

@ -6,4 +6,5 @@ Otherwise, return the GCD of `y` and the remainder of the division `x/y`.
```js ```js
const gcd = (x , y) => !y ? x : gcd(y, x % y); const gcd = (x , y) => !y ? x : gcd(y, x % y);
// gcd (8, 36) -> 4
``` ```

View File

@ -4,4 +4,5 @@ Return `arr[0]`.
```js ```js
const head = arr => arr[0]; const head = arr => arr[0];
// head([1,2,3]) -> 1
``` ```

View File

@ -4,4 +4,5 @@ Return `arr.slice(0,-1)`.
```js ```js
const initial = arr => arr.slice(0,-1); const initial = arr => arr.slice(0,-1);
// initial([1,2,3]) -> [1,2]
``` ```

View File

@ -6,4 +6,5 @@ You can omit `start` to use a default value of `0`.
```js ```js
const initializeArrayRange = (end, start = 0) => const initializeArrayRange = (end, start = 0) =>
Array.apply(null, Array(end-start)).map( (v,i) => i + start ); Array.apply(null, Array(end-start)).map( (v,i) => i + start );
// initializeArrayRange(5) -> [0,1,2,3,4]
``` ```

View File

@ -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`. You can omit `v` to use a default value of `0`.
```js ```js
const initializeArray = (n, v = 0) => const initializeArray = (n, v = 0) => Array(n).fill(v);
Array(n).fill(v); // initializeArray(5, 2) -> [2,2,2,2,2]
``` ```

View File

@ -4,4 +4,5 @@ Return `arr.slice(-1)[0]`.
```js ```js
const last = arr => arr.slice(-1)[0]; const last = arr => arr.slice(-1)[0];
// last([1,2,3]) -> 3
``` ```

View File

@ -9,4 +9,5 @@ const timeTaken = (f,...args) => {
console.log(performance.now() - t0); console.log(performance.now() - t0);
return r; return r;
} }
// timeTaken(Math.pow, 2, 10) -> 1024 (0.010000000009313226 logged in console)
``` ```

View File

@ -3,5 +3,6 @@
Use `Array.reduce()` to create and combine key-value pairs. Use `Array.reduce()` to create and combine key-value pairs.
```js ```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}
``` ```

View File

@ -5,4 +5,5 @@ Use `reduce()` combined with `map()` to iterate over elements and combine into a
```js ```js
const powerset = arr => const powerset = arr =>
arr.reduce( (a,v) => a.concat(a.map( r => [v].concat(r) )), [[]]); arr.reduce( (a,v) => a.concat(a.map( r => [v].concat(r) )), [[]]);
// powerset([1,2]) -> [[], [1], [2], [2,1]]
``` ```

View File

@ -4,4 +4,5 @@ Use `Math.random()` to generate a random value, map it to the desired range usin
```js ```js
const randomInRange = (min, max) => Math.random() * (max - min) + min; const randomInRange = (min, max) => Math.random() * (max - min) + min;
// randomInRange(2,10) -> 6.0211363285087005
``` ```

View File

@ -3,5 +3,6 @@
Use `sort()` to reorder elements, utilizing `Math.random()` to randomize the sorting. Use `sort()` to reorder elements, utilizing `Math.random()` to randomize the sorting.
```js ```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]
``` ```

View File

@ -6,4 +6,5 @@ Pass a second argument to simulate a link click (`true` - default) or an HTTP re
```js ```js
const redirect = (url, asLink = true) => const redirect = (url, asLink = true) =>
asLink ? window.location.href = url : window.location.replace(url); asLink ? window.location.href = url : window.location.replace(url);
// redirect('https://google.com')
``` ```

View File

@ -5,4 +5,5 @@ Combine characters to get a string using `join('')`.
```js ```js
const reverseString = str => [...str].reverse().join(''); const reverseString = str => [...str].reverse().join('');
// reverseString('foobar') -> 'raboof'
``` ```

View File

@ -11,4 +11,5 @@ const scrollToTop = _ => {
window.scrollTo(0, c - c/8); window.scrollTo(0, c - c/8);
} }
} }
// scrollToTop()
``` ```

View File

@ -3,5 +3,6 @@
Use `filter()` to remove values that are not part of `values`, determined using `includes()`. Use `filter()` to remove values that are not part of `values`, determined using `includes()`.
```js ```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]
``` ```

View File

@ -5,4 +5,5 @@ Split the string using `split('')`, `sort()` utilizing `localeCompare()`, recomb
```js ```js
const sortCharactersInString = str => const sortCharactersInString = str =>
str.split('').sort( (a,b) => a.localeCompare(b) ).join(''); str.split('').sort( (a,b) => a.localeCompare(b) ).join('');
// sortCharactersInString('cabbage') -> 'aabbceg'
``` ```

View File

@ -5,4 +5,5 @@ Use `reduce()` to add each value to an accumulator, initialized with a value of
```js ```js
const sum = arr => const sum = arr =>
arr.reduce( (acc , val) => acc + val, 0); arr.reduce( (acc , val) => acc + val, 0);
// sum([1,2,3,4]) -> 10
``` ```

View File

@ -4,4 +4,5 @@ Use array destructuring to swap values between two variables.
```js ```js
[varA, varB] = [varB, varA]; [varA, varB] = [varB, varA];
// [x, y] = [y, x]
``` ```

View File

@ -4,4 +4,5 @@ Return `arr.slice(1)`.
```js ```js
const tail = arr => arr.slice(1); const tail = arr => arr.slice(1);
// tail([1,2,3]) -> [2,3]
``` ```

View File

@ -5,4 +5,5 @@ Use `isFinite()` to check if the number is finite.
```js ```js
const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n); const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n);
// validateNumber('10') -> true
``` ```