kolodny / immutability-helper

mutate a copy of data without changing the original source
MIT License
5.17k stars 186 forks source link

can Immutability helper be used to $push to the beginning/start of an array? #153

Closed HendrikPetertje closed 4 years ago

HendrikPetertje commented 4 years ago

Hi there! I've been really enjoying your library in all kinds of projects so far. For one project we're adding a comment section where new comments coming in are displayed at the top. as such I'd like to push new incoming messages (statefull values) to the start of an array.

I've been using:

fromSocket = {
  comment: {
    message: 'foo',
    from: 'Piere',
    at: 'some date',
  },
},

// and then in the immutable helper:

{ comments: { $push: [fromSocket.comment] } }

Is it possible to $push to the start (or a specific position) in an array?

kolodny commented 4 years ago

Yes! You can use the $splice method:

https://stackblitz.com/edit/typescript-dpyqpy?file=index.ts

import update from 'immutability-helper';

console.log(update)

const state = [
  {id: 1, text: 'hello'},
  {id: 10, text: 'goodbye'}
];

const beginning = update(state, {
  $splice: [[0, 0, {id: 0, text: 'before'}]]
});

console.log({ beginning });

const middle = update(state, {
  $splice: [[1, 0, {id: 2, text: 'test'}]]
});

console.log({ middle })

The first argument of the splice array is the position where the new element should be inserted, the next should probably always be zero in your case and the third is the new element

HendrikPetertje commented 4 years ago

That is super neat and intuitive! Thanks!

HendrikPetertje commented 4 years ago

My colleague turned around in his seat, looked at me and said.

Well if splice works on that lib, doesn't it take unshift?

low and behold: https://github.com/kolodny/immutability-helper/blob/3f3e7855682643eca7f170ff6534b09b27862d9b/test.ts#L55

so for the future wanderer that finds this issue: jep you can use splice (which is a super neat way to modify arrays), but if you're just interested in putting stuff in the start of an array. unshift!