Last active
May 14, 2021 16:22
-
-
Save norami/fe3978cc1b1d05b44682e17a61e2786d to your computer and use it in GitHub Desktop.
なるべく古いオブジェクトを残しつつ、新しいオブジェクトをコピーしたものを返す
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
多階層オブジェクトをイミュータブルに管理する状況で、差分処理のコストを抑制するために汎用的に使えるコード。