Skip to content

Instantly share code, notes, and snippets.

@navneet-kumar
Last active May 31, 2020 05:12
Show Gist options
  • Select an option

  • Save navneet-kumar/cd210707bbf6150747c6786ea744f488 to your computer and use it in GitHub Desktop.

Select an option

Save navneet-kumar/cd210707bbf6150747c6786ea744f488 to your computer and use it in GitHub Desktop.
Array Immutability in JS

Array

Immutable operations (Add,remove, update) in a array

  const number = [1,2,3];

  // add at the end
  const addedAtEnd = [...number,4];
  
  // add in between
  const index = number.indexOf(2);
  const addedInBetween = [
    ...number.slice(0,index),
    4,
    ...number.slice(index),
  ];
  
  // add at the beginning
  const addedAtBegin = [ 4 , ...number ];
  
  // removing an element
  const removed = number.filter(n => n !==2);
  
  //update an element
  const updated = number.map(n=>(n === 2 ? 20 : n));
  

Famous libraries for immutability

  • immutable

    import {Map} from "immutable";
    
    let book = Map({title: "wings of fire"});
    
    function publish(book){
      return book.set("isPublish", true);
    }
    
    book = publish(book);
    
    console.log(book.toJs());  
  • (immer)[https://immerjs.github.io/immer/docs/introduction]

    import {produce} from "immer";
    
    let book = Map({title: "wings of fire"});
    
    function publish(book){
      return produce(book, (draft) => {
        draft.isPublish = true;
      });
    }
    
    let updated = publish(book);
    
    console.log(book);  
    console.log(updated);  
  • mori

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment