@rbxts/jsnatives
Object.diff
Computes the difference between two objects, returning the changes needed to transform the second object into the first object.
Signature
function diff<T, U, Deep extends boolean>(current: T, other: U, deep?: Deep): Diff<T, U, Deep>Description
The Object.diff() method computes the difference between two objects, returning an object that represents the changes needed to transform the second object (other) into the first object (current). This is particularly useful for tracking changes in state management and synchronization.
The diffDeletedSymbol is a special symbol used internally to mark deleted properties in the diff result., when other has a key, that is not in current, it will be marked as deleted using this symbol.
Examples
Basic diff computation
const current = { a: 1, b: 2, c: 3 };const other = { a: 1, b: 4, d: 5 };
const result = Object.diff(current, other);print(result); // { b: 2, c: 3, d: {} (diffDeletedSymbol) }Deep diff computation
if deep is true, 2 tables will be compared recursively instead of using a shallow comparison.
const current = { user: { name: "John", age: 30 }};const other = { user: { name: "John", age: 31 }};
const result = Object.diff(current, other, true);print(result); // { user: { age: 30 } }Notes
- The
diffDeletedSymbolis an internal implementation detail and should not be used directly in application code, or only when making custom diff implementations tu use in Object.patch. - When using deep diff, nested objects are compared recursively, but no cache or limit is implemented, so self-referencing tables will cause a stack overflow if you want to support that, you will need to implement your own recursive algorithm implementing Object.diff(a, b, false).
- The diff result can be used with
Object.patch()to transform the second object into the first object - The diff operation is designed so that
patch(other, diff(current, other))will transformotherto matchcurrent, so after patching, Object.equals(patch(other, diff(current, other)), current) will normally be true.