DEV Community

Cover image for Immutable Splice in Javascript
Kurapati Mahesh
Kurapati Mahesh

Posted on • Edited on

Immutable Splice in Javascript

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'] 
Enter fullscreen mode Exit fullscreen mode

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'] 
Enter fullscreen mode Exit fullscreen mode

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

  1. Like - You reached here means. I think, I deserve a like.
  2. Comment - We can learn together.
  3. Share - Makes others also find this resource useful.
  4. Subscribe / Follow - to stay up to date with my daily articles.
  5. Encourage me - You can buy me a Coffee

Let's discuss further.

  1. Just DM @urstrulyvishwak
  2. Or mention
    @urstrulyvishwak

For further updates:

Follow @urstrulyvishwak

Top comments (2)

Collapse
 
irvingarmenta profile image
Irving Armenta

@urstrulyvishwak

Thanks for the snippet, however,
I would change count to a const instead of let since there is no re-assignment.

and let me add here the typescript version

function splice<T>(arr: T[], start: number, deleteCount: number, ...addItem: T[]) { const result = []; if (start > 0) { result.push(...arr.slice(0, start)); } result.push(...addItem); const len = result.length - addItem.length; const count = deleteCount <= 0 ? len : len + deleteCount; if (arr[count]) { result.push(...arr.slice(count)); } return result; } 
Enter fullscreen mode Exit fullscreen mode

cheers ~

Collapse
 
urstrulyvishwak profile image
Kurapati Mahesh

Good one