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
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'
```
```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
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);
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).
```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), {}) )) ( );
/*
```
```js
const squareIt = arr => mapObject(arr, a => a*a)
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);
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
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
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
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
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;
}, 0)
);
/*
```
```js
const users = [{ 'name': 'fred', 'age': 48 },{ 'name': 'barney', 'age': 36 },
{ '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']) -> [{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,'');
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
const percentile = (arr, val) =>
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
const pick = (obj, arr) =>
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
const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));
/*
```
```js
const add5 = x => x + 5
const multiply = (x, y) => x * y
const multiplyAndAdd5 = pipeFunctions(multiply, add5)
multiplyAndAdd5(5, 2) -> 15
*/
```

View File

@ -7,5 +7,8 @@ Use `Array.reduce()` combined with `Array.map()` to iterate over elements and co
```js
const powerset = arr =>
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.
@ -6,11 +6,14 @@ 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),
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;
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) =>
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) => {
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));
};
// let myArray1 = ['a', 'b', 'c', 'a', 'b', 'c'];
// pull(myArray1, 'a', 'c');
// console.log(myArray1) -> [ 'b', 'b' ]
// let myArray2 = ['a', 'b', 'c', 'a', 'b', 'c'];
// pull(myArray2, ['a', 'c']);
// console.log(myArray2) -> [ 'b', 'b' ]
```
```js
let myArray1 = ['a', 'b', 'c', 'a', 'b', 'c'];
pull(myArray1, 'a', 'c');
console.log(myArray1) -> [ 'b', 'b' ]
let myArray2 = ['a', 'b', 'c', 'a', 'b', 'c'];
pull(myArray2, ['a', 'c']);
console.log(myArray2) -> [ 'b', 'b' ]
```