如何从表示更改的对象数组中获取最终状态

How to get the final state from an array of objects representing 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,
  },
]

我希望这个数组包含每个项目的最终状态:

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

目前,我使用的逻辑是这个。但是它不能正常工作。

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);
};

你能帮我解决这个问题吗?

提前致谢!

item1存储在finalChanges中时,您不能再次读取这个修改后的对象,否则您将访问到新的更新值。在修改之前,您需要为每次迭代创建未修改对象的副本。

如果不存在,就从主项中获取我们要设置的值。

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: new Date(notAlteredItem[item1.id]?.timestamp ?? item1.timestamp)
    };
  }

  return Object.values(finalState);
};

检查这个沙盒https://codesandbox.io/s/zen-johnson-dkxk0?file=/src/index.js