Module ringo/utils/objects
Adds utility functions for working with JavaScript Objects
clone (object, circular, depth, prototype)
Creates a deep clone (full copy) of the given object.
It supports cloning objects with circular references by tracking visited properties. Only if the object to clone cannot hold any circular reference by foreknowledge, tracking can be turned off to save CPU and memory.
Example
let objects = require("ringo/utils/objects");
let a = [1, 2, 3];
// shallow clone: b.a and c.a will share the same array
let b = objects.clone(a);
a[0] = 100;
console.dir(a); // -> [ 100, 2, 3 ]
console.dir(b); // -> [ 1, 2, 3 ]
let root = { simple: 1 };
let circle = { circ: root };
root.circle = circle;
let copy = objects.clone(root);
console.dir(root); // -> { simple: 1, circle: { circ: [CyclicRef] }}
console.dir(copy); // -> { simple: 1, circle: { circ: [CyclicRef] }}
// endless loop, throws a java.lang.StackOverflowError
let danger = objects.clone(root, false);
// limiting the depth might lead to shallow clones!
let tree = { root: 1, a: { b: { c: { d: { e: "foo" } } } } };
let fullClone = objects.clone(tree);
let shallowClone = objects.clone(tree, true, 1);
tree.root = 2; // depth = 1
tree.a.b.c.d.e = "bar"; // depth = 5
console.log(tree.root); // --> 2
console.dir(tree.a.b.c.d); // --> { e: 'bar' }
console.log(fullClone.root); // --> 1
console.dir(fullClone.a.b.c.d); // --> { e: 'foo' }
console.log(shallowClone.root); // --> 1
console.dir(shallowClone.a.b.c.d); // --> { e: 'bar' }
Parameters
Object | object | the object to clone |
Boolean | circular | (optional, default true) true if the object to be cloned may contain circular references |
Number | depth | (optional, default Infinity) limits the non-shallow clone of an object to a particular depth |
Object | prototype | (optional) sets the prototype to be used when cloning an object |
Returns
Object | the clone object |
See
merge (obj...)
Creates a new object as the as the keywise union of the provided objects. Whenever a key exists in a later object that already existed in an earlier object, the according value of the earlier object takes precedence.
Example
const a = { "k1": "val-A" };
const b = { "k1": "val-B", "k2": "val-B" };
const c = { "k1": "val-C", "k2": "val-C" };
// result: { k1: 'val-A', k2: 'val-B' }
const result = objects.merge(a, b, c);
Parameters
Object... | obj... | The objects to merge |