Add offset snippet

This commit is contained in:
Angelos Chalaris
2018-04-10 19:07:50 +03:00
parent 7cea814b6e
commit 6405c7f14d
6 changed files with 1104 additions and 1056 deletions

16
snippets/offset.md Normal file
View File

@ -0,0 +1,16 @@
### offset
Moves the specified amount of elements to the end of the array.
Use `Array.slice()` twice to get the elements after the specified index and the elements before that.
Use the spread operator(`...`) to combine the two into one array.
If `offset` is negative, the elements will be moved from end to start.
```js
const offset = (arr, offset) => [...arr.slice(offset), ...arr.slice(0, offset)];
```
```js
offset([1, 2, 3, 4, 5], 2); // [3, 4, 5, 1, 2]
offset([1, 2, 3, 4, 5], -2); // [4, 5, 1, 2, 3]
```