-
Notifications
You must be signed in to change notification settings - Fork 0
Helper
Some useful helper functions wrote for RichJSON in order to work properly, maybe you find some use cases too.
Merges two or more objects into a new, separate object. It iterates through all provided objects and uses deep merging to combine their properties.
import {mergeObjects} from "@rjson/parser"
const obj1 = { a: 1, nested: { b: 2 } };
const obj2 = { c: 3, nested: { d: 4 } };
const combined = mergeObjects(obj1, obj2);
// Result: { a: 1, c: 3, nested: { b: 2, d: 4 } }Merges one or more source objects directly into a target object. This modifies the target object in place and returns it. It includes protection against circular dependencies.
import {mergeIntoTarget} from "@rjson/parser"
const target = { a: 1 };
const source = { b: 2 };
mergeIntoTarget(target, source);
// target is now: { a: 1, b: 2 }Creates a new object and merges multiple source objects into it. Unlike the standard mergeObjects, this version does not rebind functions to the new object; functions retain their original execution context.
import {mergeObjectsWithoutRebind} from "@rjson/parser"
const obj1 = { val: 10 };
const obj2 = {
val: 20
getVal: function() { return this.val; }
};
const merged = mergeObjectsWithoutRebind(obj1, obj2);
console.log(merged.getVal()) // Output: 20
// merged.getVal() will attempt to find 'val' on its original
// context rather than being bound to the new 'merged' object.Functions exactly like mergeIntoTarget, but when it encounters a function, it assigns the function directly to the target without binding it to the target's context.
import {mergeIntoWithoutRebind} from "@rjson/parser"
const target = {};
const source = {
log: function() { console.log(this); }
};
mergeIntoWithoutRebind(target, source);
// target.log is the original function, not bound to target.Creates a deep clone of an object or array. It handles circular dependencies by tracking object addresses and automatically rebinds functions to the new cloned instance.
import {cloneObject} from "@rjson/parser"
const original = { a: 1, b: { c: 2 } };
original.self = original; // Circular reference
const copy = cloneObject(original);
// copy.self points to copy, not originalAuthor’s Recommendation: next read Resolve Order
Back to Repo ● Wiki Home
Copyright © Maximilian Schwarz