Splice
by default mutates/changes/updates inputted array in Javascript. For example:
const test = ['angel', 'clown', 'mandarin', 'sturgeon'];
test.splice(2, 1, 'first');
console.log(test);
> ['angel', 'clown', 'first', 'sturgeon']
If you see in above example splice
mutates original array.
We can create immutable splice function in Javascript.
Here we go:
function splice(arr, start, deleteCount, ...addItem) {
const result = [];
if (start > 0) {
result.push(...arr.slice(0, start));
}
result.push(...addItem);
const len = result.length - addItem.length;
let count = deleteCount <= 0 ? len : len + deleteCount;
if (arr[count]) {
result.push(...arr.slice(count));
}
return result;
}
const test = ['angel', 'clown', 'mandarin', 'sturgeon'];
console.log(splice(test, 2, 1, 'drum'));
> ['angel', 'clown', 'drum', 'sturgeon']
console.log(test)
> ['angel', 'clown', 'mandarin', 'sturgeon']
test
array in above example isn't mutated.
Welcoming suggestions/concerns. Always happy to update article for any use case.
Thank you! Happy experimenting.
💎 Love to see your response
- Like - You reached here means. I think, I deserve a like.
- Comment - We can learn together.
- Share - Makes others also find this resource useful.
- Subscribe / Follow - to stay up to date with my daily articles.
- Encourage me - You can buy me a Coffee
Let's discuss further.
- Just DM @urstrulyvishwak
-
Or mention
@urstrulyvishwak
Top comments (2)
@urstrulyvishwak
Thanks for the snippet, however,
I would change
count
to aconst
instead oflet
since there is no re-assignment.and let me add here the typescript version
cheers ~
Good one