tiny-merge-patch
Version:
JSON Merge Patch (RFC 7396) Implementation
26 lines (25 loc) • 735 B
JavaScript
/**
* Test if a value is a plain object.
*/
const isObject = (val) => val != null && typeof val === "object" && Array.isArray(val) === false;
/**
* Apply a JSON merge patch. The origin is not modified, but unchanged
* properties are recycled.
*/
export function apply(origin, patch) {
if (!isObject(patch)) {
// If the patch is not an object, it replaces the origin.
return patch;
}
const result = !isObject(origin) ? {} : { ...origin };
for (const [key, patchVal] of Object.entries(patch)) {
if (patchVal === null) {
delete result[key];
}
else {
result[key] = apply(result[key], patchVal);
}
}
return result;
}
export default apply;