Home > Software design >  Making a faster executing sort function
Making a faster executing sort function

Time:08-29

I have a data set thats over 1000 items and the issue Im having is the amount of time it takes for the table to be sorted. Ive built a few tables recently and the sort function Ive been using has always been sufficient until now I am assuming its the size data thats causing it to return so slow? I dont have the option of doing this on the backend. Im not sure how to update the loading state in my function properly so the time between when the sort is clicked and the and sorted data is returned is at least showing loading.

this is my sort function and Im wondering if there is any way to optimize it:

const sortTable = (field, order) => {
    let sorted = formItems?.sort((a, b) => {
        setLoading(true)
        if (order === "asc") {
            return a[field] > b[field] ? 1 : -1;
        } else {
            return a[field] < b[field] ? 1 : -1;
        }
    })
    setLoading(false)
    setFormItems(sorted)
}

CodePudding user response:

Move your condition and setLoading funtion outside of sort funtion

const sortTable = (field, order) => {
   setLoading(true)
   Var sorted = []
   if (order === "asc") {
     sorted = formItems?.sort((a, b) => a[field] > b[field] ? 1 : -1)
    } else {
      sorted = formItems?.sort((a, b) =>  a[field] < b[field] ? 1 : -1)
    }
    setLoading(false)
    setFormItems(sorted)
}

CodePudding user response:

try this:

const sortTable = (field, order) => {
  // run just once
  setLoading(true);

  // avoid batching (react < 18)
  setTimeout(() => {
    // change value based on previous state
    setFormItems((prev) => {
      if (!prev) return prev; // avoid optional chaining (subjective)
      const formItemsCopy = [...prev]; // stay immutable

      // simplify
      const x = order === 'asc' ? 1 : -1;
      formItemsCopy.sort((a, b) => {
        return (a[field] - b[field]) * x;
      });
    });

    setLoading(false);
  }, 0);
};
  • Related