Home > Mobile >  How to get the final state from an array of objects representing changes
How to get the final state from an array of objects representing changes

Time:12-08

I have an array of changes (objects) and would like to get the final state after all the changes have been made.

For example, having this array of changes:

const today = new Date();
const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);
const tomorrow = new Date(today);
tomorrow.setDate(tomorrow.getDate()   1);

const item1 = {
  id: 'id1',
  timestamp: yesterday,
};
const item2 = {
  id: 'id2',
  timestamp: today,
};
const item3 = {
  id: 'id3',
  timestamp: tomorrow,
};

const changes = [
  {
    action: 'swap',
    item1,
    item2,
  },
  {
    action: 'swap',
    item1,
    item2: item3,
  },
]

I am expecting this array with the final state of each item:

const finalState = [
  {
    id: item1.id,
    timestamp: item3.timestamp,
  },
  {
    id: item2.id,
    timestamp: item1.timestamp,
  },
  {
    id: item3.id,
    timestamp: item2.timestamp,
  },
]

currently, the logic I am using is this one. However it is not working properly.

export const convertChangesToFinalState = ({
  changes,
}): FinalChanges => {
  const finalState: {
    [id: string]: FinalChange;
  } = {};

  for (const { item1, item2 } of changes) {
    finalState[item1.id] = {
      id: item1.id,
      timestamp: new Date(finalState[item2.id]?.timestamp ?? item2.timestamp),
    };

    finalState[item2.id] = {
      id: item2.id,
      timestamp: new Date(finalState[item1.id]?.timestamp ?? item1.timestamp),
      // timestamp: new Date(new Date(item2.timestamp).getTime() !== new Date(finalState[item1.id]?.timestamp).getTime()? finalState[item1.id]?.timestamp : item1.timestamp),
    };
  }

  return Object.values(finalState);
};

Could you please help me solve this?

Thank you in advance!

CodePudding user response:

When the item1 is stored in the finalChanges, you cannot read again this modified object, otherwise you will be accessing to the new updated value. You will need to create a copy of the non-modified object for each iteration, before modifying it.

If it doesn´t exist, just get the value we want to set from the main item.

export const convertChangesToFinalState = ({
  changes,
}): FinalChanges => {
  const finalState: {
    [id: string]: FinalChange;
  } = {};

  for (const { item1, item2 } of changes) {
    const notAlteredItem = { ...finalState };
    finalState[item1.id] = {
      id: item1.id,
      timestamp: new Date(finalState[item2.id]?.timestamp ?? item2.timestamp),
    };

    finalState[item2.id] = {
      id: item2.id,
      timestamp: notAlteredItem[item1.id]?.timestamp ?? item1.timestamp
    };
  }

  return Object.values(finalState);
};

Check this sandbox https://codesandbox.io/s/zen-johnson-dkxk0?file=/src/index.js

  • Related