Add aperture

This commit is contained in:
Angelos Chalaris
2020-05-13 13:25:33 +03:00
parent 3e5f837e2f
commit f6ba4862ea

22
snippets/aperture.md Normal file
View File

@ -0,0 +1,22 @@
---
title: aperture
tags: array,intermediate
---
Returns an array of `n`-tuples of consecutive elements.
Use `Array.prototype.slice()` and `Array.prototype.map()` to create an array of appropriate length and populate it with `n`-tuples of consecutive elements from `arr`.
If `n` is greater than the length of `arr`, return an empty array.
```js
const aperture = (n, arr) =>
n > arr.length
? []
: arr.slice(n - 1).map((v, i) => [...arr.slice(i, i + n - 1), v]);
```
```js
R.aperture(2, [1, 2, 3, 4]); // [[1, 2], [2, 3], [3, 4]]
R.aperture(3, [1, 2, 3, 4]); // [[1, 2, 3], [2, 3, 4]]
R.aperture(5, [1, 2, 3, 4]); // []
```