update snippets 78 - 96

This commit is contained in:
Stefan Feješ
2017-12-25 14:33:49 +01:00
parent 55bc1ec632
commit bc58a5bf54
18 changed files with 86 additions and 39 deletions

View File

@ -7,5 +7,8 @@ Use `fs.writeFile()`, template literals and `JSON.stringify()` to write a `json`
```js ```js
const fs = require('fs'); 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' ```
```js
JSONToFile({test: "is passed"}, 'testJsonFile') -> writes the object to 'testJsonFile.json'
``` ```

View File

@ -6,5 +6,8 @@ Use `arr.length - 1` to compute the index of the last element of the given array
```js ```js
const last = arr => arr[arr.length - 1]; const last = arr => arr[arr.length - 1];
// last([1,2,3]) -> 3 ```
```js
last([1,2,3]) -> 3
``` ```

View File

@ -10,5 +10,8 @@ const lcm = (x,y) => {
const gcd = (x, y) => !y ? x : gcd(y, 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 ```
```js
lcm(12,7) -> 84
``` ```

View File

@ -5,10 +5,11 @@ 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). 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 ```js
const mapObject = (arr, fn) => const mapObject = (arr, fn) =>
(a => (a = [arr, arr.map(fn)], a[0].reduce( (acc,val,ind) => (acc[val] = a[1][ind], acc), {}) )) ( ); (a => (a = [arr, arr.map(fn)], a[0].reduce( (acc,val,ind) => (acc[val] = a[1][ind], acc), {}) )) ( );
/* ```
```js
const squareIt = arr => mapObject(arr, a => a*a) const squareIt = arr => mapObject(arr, a => a*a)
squareIt([1,2,3]) // { 1: 1, 2: 4, 3: 9 } squareIt([1,2,3]) // { 1: 1, 2: 4, 3: 9 }
*/
``` ```

View File

@ -10,6 +10,9 @@ const median = arr => {
const mid = Math.floor(arr.length / 2), nums = [...arr].sort((a, b) => a - b); const mid = Math.floor(arr.length / 2), nums = [...arr].sort((a, b) => a - b);
return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2; return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;
}; };
// median([5,6,50,1,-5]) -> 5 ```
// median([0,10,-2,7]) -> 3.5
```js
median([5,6,50,1,-5]) -> 5
median([0,10,-2,7]) -> 3.5
``` ```

View File

@ -6,6 +6,9 @@ Take a predicate function and apply `not` to it with its arguments.
```js ```js
const negate = func => (...args) => !func(...args); const negate = func => (...args) => !func(...args);
// filter([1, 2, 3, 4, 5, 6], negate(isEven)) -> [1, 3, 5] ```
// negate(isOdd)(1) -> false
```js
filter([1, 2, 3, 4, 5, 6], negate(isEven)) -> [1, 3, 5]
negate(isOdd)(1) -> false
``` ```

View File

@ -8,6 +8,9 @@ Omit the second argument, `n`, to get the first element of the array.
```js ```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'
```js
nthElement(['a','b','c'],1) -> 'b'
nthElement(['a','b','b'],-3) -> 'a'
``` ```

View File

@ -6,5 +6,8 @@ Use `Array.reduce()` to create and combine key-value pairs.
```js ```js
const objectFromPairs = arr => arr.reduce((a, v) => (a[v[0]] = v[1], a), {}); const objectFromPairs = arr => arr.reduce((a, v) => (a[v[0]] = v[1], a), {});
// objectFromPairs([['a',1],['b',2]]) -> {a: 1, b: 2} ```
```js
objectFromPairs([['a',1],['b',2]]) -> {a: 1, b: 2}
``` ```

View File

@ -6,5 +6,8 @@ Use `Object.keys()` and `Array.map()` to iterate over the object's keys and prod
```js ```js
const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]); const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]);
// objectToPairs({a: 1, b: 2}) -> [['a',1],['b',2]]) ```
```js
objectToPairs({a: 1, b: 2}) -> [['a',1],['b',2]])
``` ```

View File

@ -16,10 +16,11 @@ const orderBy = (arr, props, orders) =>
return acc; return acc;
}, 0) }, 0)
); );
/* ```
```js
const users = [{ 'name': 'fred', 'age': 48 },{ 'name': 'barney', 'age': 36 }, const users = [{ 'name': 'fred', 'age': 48 },{ 'name': 'barney', 'age': 36 },
{ 'name': 'fred', 'age': 40 },{ 'name': 'barney', 'age': 34 }]; { 'name': 'fred', 'age': 40 },{ 'name': 'barney', 'age': 34 }];
orderby(users, ['name', 'age'], ['asc', 'desc']) -> [{name: 'barney', age: 36}, {name: 'barney', age: 34}, {name: 'fred', age: 48}, {name: 'fred', age: 40}] orderby(users, ['name', 'age'], ['asc', 'desc']) -> [{name: 'barney', age: 36}, {name: 'barney', age: 34}, {name: 'fred', age: 48}, {name: 'fred', age: 40}]
orderby(users, ['name', 'age']) -> [{name: 'barney', age: 34}, {name: 'barney', age: 36}, {name: 'fred', age: 40}, {name: 'fred', age: 48}] orderby(users, ['name', 'age']) -> [{name: 'barney', age: 34}, {name: 'barney', age: 36}, {name: 'fred', age: 40}, {name: 'fred', age: 48}]
*/
``` ```

View File

@ -10,5 +10,8 @@ const palindrome = str => {
const s = str.toLowerCase().replace(/[\W_]/g,''); const s = str.toLowerCase().replace(/[\W_]/g,'');
return s === s.split('').reverse().join(''); return s === s.split('').reverse().join('');
} }
// palindrome('taco cat') -> true ```
```
```js
palindrome('taco cat') -> true
```

View File

@ -7,5 +7,8 @@ Use `Array.reduce()` to calculate how many numbers are below the value and how m
```js ```js
const percentile = (arr, val) => const percentile = (arr, val) =>
100 * arr.reduce((acc,v) => acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0), 0) / arr.length; 100 * arr.reduce((acc,v) => acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0), 0) / arr.length;
// percentile([1,2,3,4,5,6,7,8,9,10], 6) -> 55 ```
```
```js
percentile([1,2,3,4,5,6,7,8,9,10], 6) -> 55
```

View File

@ -7,5 +7,8 @@ Use `Array.reduce()` to convert the filtered/picked keys back to an object with
```js ```js
const pick = (obj, arr) => const pick = (obj, arr) =>
arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {}); arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {});
// pick({ 'a': 1, 'b': '2', 'c': 3 }, ['a', 'c']) -> { 'a': 1, 'c': 3 } ```
```js
pick({ 'a': 1, 'b': '2', 'c': 3 }, ['a', 'c']) -> { 'a': 1, 'c': 3 }
``` ```

View File

@ -7,10 +7,11 @@ The first (leftmost) function can accept one or more arguments; the remaining fu
```js ```js
const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));
/* ```
```js
const add5 = x => x + 5 const add5 = x => x + 5
const multiply = (x, y) => x * y const multiply = (x, y) => x * y
const multiplyAndAdd5 = pipeFunctions(multiply, add5) const multiplyAndAdd5 = pipeFunctions(multiply, add5)
multiplyAndAdd5(5, 2) -> 15 multiplyAndAdd5(5, 2) -> 15
*/
``` ```

View File

@ -7,5 +7,8 @@ Use `Array.reduce()` combined with `Array.map()` to iterate over elements and co
```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]] ```
```js
powerset([1,2]) -> [[], [1], [2], [2,1]]
``` ```

View File

@ -1,4 +1,4 @@
### primes ### primes
Generates primes up to a given number, using the Sieve of Eratosthenes. Generates primes up to a given number, using the Sieve of Eratosthenes.
@ -6,11 +6,14 @@ Generate an array from `2` to the given number. Use `Array.filter()` to filter o
```js ```js
const primes = num => { const primes = num => {
let arr = Array.from({length:num-1}).map((x,i)=> i+2), let arr = Array.from({length:num-1}).map((x,i)=> i+2),
sqroot = Math.floor(Math.sqrt(num)), sqroot = Math.floor(Math.sqrt(num)),
numsTillSqroot = Array.from({length:sqroot-1}).map((x,i)=> i+2); numsTillSqroot = Array.from({length:sqroot-1}).map((x,i)=> i+2);
numsTillSqroot.forEach(x => arr = arr.filter(y => ((y%x)!==0)||(y==x))); numsTillSqroot.forEach(x => arr = arr.filter(y => ((y%x)!==0)||(y==x)));
return arr; return arr;
} }
// primes(10) -> [2,3,5,7] ```
```js
primes(10) -> [2,3,5,7]
``` ```

View File

@ -14,6 +14,9 @@ const promisify = func =>
func(...args, (err, result) => func(...args, (err, result) =>
err ? reject(err) : resolve(result)) err ? reject(err) : resolve(result))
); );
// const delay = promisify((d, cb) => setTimeout(cb, d)) ```
// delay(2000).then(() => console.log('Hi!')) -> Promise resolves after 2s
```js
const delay = promisify((d, cb) => setTimeout(cb, d))
delay(2000).then(() => console.log('Hi!')) -> // Promise resolves after 2s
``` ```

View File

@ -11,15 +11,17 @@ _(For a snippet that does not mutate the original array see [`without`](#without
const pull = (arr, ...args) => { const pull = (arr, ...args) => {
let argState = Array.isArray(args[0]) ? args[0] : args; let argState = Array.isArray(args[0]) ? args[0] : args;
let pulled = arr.filter((v, i) => !argState.includes(v)); let pulled = arr.filter((v, i) => !argState.includes(v));
arr.length = 0; arr.length = 0;
pulled.forEach(v => arr.push(v)); pulled.forEach(v => arr.push(v));
}; };
```
// let myArray1 = ['a', 'b', 'c', 'a', 'b', 'c'];
// pull(myArray1, 'a', 'c'); ```js
// console.log(myArray1) -> [ 'b', 'b' ] let myArray1 = ['a', 'b', 'c', 'a', 'b', 'c'];
pull(myArray1, 'a', 'c');
// let myArray2 = ['a', 'b', 'c', 'a', 'b', 'c']; console.log(myArray1) -> [ 'b', 'b' ]
// pull(myArray2, ['a', 'c']);
// console.log(myArray2) -> [ 'b', 'b' ] let myArray2 = ['a', 'b', 'c', 'a', 'b', 'c'];
pull(myArray2, ['a', 'c']);
console.log(myArray2) -> [ 'b', 'b' ]
``` ```