Factorial and powerset

This commit is contained in:
Angelos Chalaris
2017-12-07 14:41:33 +02:00
parent be3c075f12
commit d336333f9e
3 changed files with 36 additions and 0 deletions

8
snippets/factorial.md Normal file
View File

@ -0,0 +1,8 @@
### Factorial
Create an array of length `n+1`, use `reduce()` to get the product of every value in the given range, utilizing the index of each element.
```js
var factorial = n =>
Array.apply(null, [1].concat(Array(n))).reduce( (a, _, i) => a * i || 1 , 1);
```

8
snippets/powerset.md Normal file
View File

@ -0,0 +1,8 @@
### Powerset
Use `reduce()` combined with `map()` to iterate over elements and combine into an array containing all combinations.
```js
var powerset = arr =>
arr.reduce( (a,v) => a.concat(a.map( r => [v].concat(r) )), [[]]);
```