Skip to content

Instantly share code, notes, and snippets.

@norami
Last active May 14, 2021 16:22
Show Gist options
  • Save norami/fe3978cc1b1d05b44682e17a61e2786d to your computer and use it in GitHub Desktop.
Save norami/fe3978cc1b1d05b44682e17a61e2786d to your computer and use it in GitHub Desktop.
なるべく古いオブジェクトを残しつつ、新しいオブジェクトをコピーしたものを返す
const merge = (oldValue: any, newValue: any) => {
if (oldValue === newValue) {
return oldValue;
}
if (typeof oldValue !== "object" || typeof newValue !== "object") {
return newValue;
}
const createdObj: any = {};
let changed = false;
for (const key of Object.keys(oldValue)) {
// find deleted field
if (Object.hasOwnProperty(newValue, key)) {
changed = true;
}
}
for (const key of Object.keys(newValue)) {
const temp = merge(oldValue[key], newValue[key]);
if (oldValue[key] !== temp) {
changed = true;
}
createdObj[key] = temp;
}
return changed ? createdObj : oldValue;
};
@norami
Copy link
Author

norami commented May 14, 2021

多階層オブジェクトをイミュータブルに管理する状況で、差分処理のコストを抑制するために汎用的に使えるコード。

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