Created
March 6, 2018 01:04
-
-
Save icholy/c09f3890151c65e407f94a3da16930df 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
let ref = { | |
foo: 123, | |
bar: "test" | |
}; | |
let obj = { | |
foo: 123, | |
bar: "what" | |
} | |
interface Patch { | |
empty: boolean; | |
value?: any; | |
} | |
function genericDiff(obj: any, ref: any): Patch { | |
if (obj === ref) { | |
return { empty: true }; | |
} | |
if (Array.isArray(obj)) { | |
return arrayDiff(obj, ref); | |
} | |
if (typeof obj === "object") { | |
return objectDiff(obj, ref); | |
} | |
return primitiveDiff(obj, ref); | |
} | |
function primitiveDiff(obj: any, ref: any): Patch { | |
return { | |
empty: obj === ref, | |
value: obj | |
}; | |
} | |
function arrayDiff(obj: Array<any>, ref: Array<any>): Patch { | |
if (obj.length !== ref.length) { | |
return { empty: false, value: obj }; | |
} | |
for (let i = 0; i < obj.length; i++) { | |
let p = genericDiff(obj[i], ref[i]); | |
if (!p.empty) { | |
return { empty: false, value: obj } | |
} | |
} | |
return { empty: true }; | |
} | |
function objectDiff(obj: any, ref: any): Patch { | |
let patch = { empty: true, value: {} } as Patch; | |
for (let key of Object.keys(ref)) { | |
let p = genericDiff(obj[key], ref[key]); | |
if (!p.empty) { | |
patch.empty = false; | |
patch.value[key] = p.value; | |
} | |
} | |
return patch; | |
} | |
let patch = genericDiff({ foo: ["b"] }, { foo: ["b"] }); | |
console.log(JSON.stringify(patch.value)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment