shank() - array - duplicates Array.prototype.splice() except returns a new array instead of mutating in-place

Update shank.md

Update shank.md

Update shank.js

Update shank.test.js

Update tag_database

remove testlog
This commit is contained in:
Brian Boyko
2018-09-27 00:55:30 +02:00
committed by Felix Wu
parent a4058f9a2e
commit efce13b1e1
5 changed files with 62 additions and 0 deletions

23
snippets/shank.md Normal file
View File

@ -0,0 +1,23 @@
### shank
Has the same functionality as [`Array.prototype.splice()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice), but returning a new array instead of mutating the original array.
Use `Array.slice()` and `Array.concat()` to get a new array with the new contents after removing existing elements and/or adding new elements.
Omit the second argument, `index`, to start at `0`.
Omit the third argument, `delCount`, to remove `0` elements.
Omit the fourth argument, `elements`, in order to not add any new elements.
```js
const shank = (arr, index = 0, delCount = 0, ...elements) =>
arr.slice(0, index)
.concat(elements)
.concat(arr.slice(index + delCount));
```
```js
const names = ['alpha', 'bravo', 'charlie'];
const namesAndDelta = shank(names, 1, 0, 'delta'); // [ 'alpha', 'delta', 'bravo', 'charlie' ]
const namesNoBravo = shank(names, 1, 1); // [ 'alpha', 'charlie' ]
console.log(names); // ['alpha', 'bravo', 'charlie']
```