Performance: Generate flatten parent-child-list of IDs - javascript

I'm looking for a better way to generate a map of parent-child-relations; based on specific id-pattern.
Its faster to ask for void 0 === cache[parent][child]; the expected result:
{
uuid_1: {uuid_2: {}}
uuid_2: {uuid_3: {}, uuid_4: {}}
uuid_3: {}
uuid_4: {}
}
The HTML structure:
<html id="uuid-1">
<body id="uuid-2">
<somewhere>
<whatever id="uuid-3" />
</somewhere>
<foo id="uuid-4" />
</body>
</html>
_fetch():
<1> // register as init
<2> // register as child of 1
<3>
<4 /> // register as child of 2
</3>
<5 /> // register as child of 2
</2>
</1>
Parse ~1300 elements (large menu structure) to find my ~50 uuids.
Try 1 with jQuery:
_fetch: function(element, factoryName)
{
var a = {}, l = 0, t = this, f = function(el, n)
{
if(!a[n]) a[n] = {};
var e = $(el), test = $('[id^="uuid-"]', e);
if(!test.length)
return;
e.children().each(function()
{
var u = $(this), id = u.attr('id'), q;
// anonymous element: no class defined
if(!(id && 'uuid-' === id.slice(0x00, 0x05)))
{
f(this, n); // continue with current name
return;
}
l++;
q = $.T.util.uuidFromId(id);
$.T.__dict[q] = '#' + id;
a[n][q] = {};
// comment in/out
f(this, q);
});
}
f(element, factoryName);
return a;
}
Try 2 with yellow JS:
..., g = function(n, p)
{
var r = [];
for(var d = (p || document).getElementsByTagName('*'), i = 0, l = d.length; i < l; i++)
d[i].getAttribute(n) && r.push(d[i]);
return r;
},
f = function(el, n)
{
var z = el.children.length, y = 0;
if(!a[n]) a[n] = {};
if(z && g('id', el)) for(; y < z; y++)
{
var u = el.children[y], id = u.getAttribute('id'), q;
if(!(id && 'uuid-' === id.slice(0x00, 0x05)))
{
f(u, n);
continue;
}
l++;
$.T.__dict[q = $.T.util.uuidFromId(id)] = '#' + id;
a[n][q] = {};
// it's irrelevant to fetch the full html or a sequence by constructor
//f(u, q);
}
}
My question is:
How to collect DOM elements as flat representation in a faster way; like the mapping above? My current solution is very laggy.
OT:
contextual x-dialog based on map:
<baz><alice><bob><bobchild/></bob></alice><foo />
alice._init:
before init children of bob
tell foo 'go away'
before init bob // context: no bob
after init children of alice // && alice without children
after init baz // && baz not ready -> no hello
tell baz 'hello'

I am still not quite sure I know what you're trying to do, but here's the fastest way I know to walk a DOM tree and accumulate parent/child info like you're doing to build the data structure you indicated you wanted to end up with:
var treeWalkFast = (function() {
// create closure for constants
var skipTags = {"SCRIPT": true, "IFRAME": true, "OBJECT": true,
"EMBED": true, "STYLE": true, "LINK": true, "META": true};
return function(parent, fn, allNodes) {
var parents = [];
var uuidParents = [];
parents.push(parent);
uuidParents.push(parent);
var node = parent.firstChild, nextNode, lastParent;
while (node && node != parent) {
if (allNodes || node.nodeType === 1) {
if (fn(node, parents, uuidParents) === false) {
return(false);
}
}
// if it's an element &&
// has children &&
// has a tagname && is not in the skipTags list
// then, we can enumerate children
if (node.nodeType === 1 && node.firstChild && !(node.tagName && skipTags[node.tagName])) {
// going down one level, add this item to the parent array
parents.push(node);
if (node.id && node.id.substr(0, 5) === "uuid-") {
uuidParents.push(node);
}
node = node.firstChild;
} else if (node.nextSibling) {
// node had no children so going to next sibling
node = node.nextSibling;
} else {
// no child and no nextsibling
// find parent that has a nextSibling
while ((node = node.parentNode) != parent) {
lastParent = parents.pop();
if (lastParent === uuidParents[uuidParents.length - 1]) {
uuidParents.pop();
}
if (node.nextSibling) {
node = node.nextSibling;
break;
}
}
}
}
}
})();
var objects = {uuid_1: {}};
treeWalkFast(document.documentElement, function(node, parents, uuidParents) {
if (node.id && node.id.substr(0, 5) === "uuid-") {
var uuidParent = uuidParents[uuidParents.length - 1];
if (!objects[uuidParent.id]) {
objects[uuidParent.id] = {};
}
objects[uuidParent.id][node.id] = {};
objects[node.id] = {};
}
});
Working demo here: http://jsfiddle.net/jfriend00/yzaJ6/
This is an adaptation of the treeWalkFast() function I wrote for this answer.

Related

Trying to make a function that returns selected CSS properties but is pretty laggy

I was trying to make a function that gives you the selected CSS properties of an element those you want. But it's pretty laggy if used in console as of it needs to get and match all CSS properties.
function styleOf(elementUseSelectors, propertiesToCheck, tellInConsole) {
var element = elementUseSelectors;
var Arguments = propertiesToCheck;
var calculatedProperties = [];
var matchedProperties = [];
if (tellInConsole !== undefined && tellInConsole == true) {
console.warn("Running styleOf() Please Don't Do Other Calculations This Function Disables Console.")
}
for (var i = 0; i < Object.keys(getComputedStyle(element)).length; i++) {
var value = getComputedStyle(element).getPropertyValue(Object.entries(getComputedStyle(element))[i][0].replace(/([A-Z])/g, ' $1').trim().replaceAll(" ", "-").toLowerCase());
if (value !== "") {
calculatedProperties.push(Object.entries(getComputedStyle(element))[i][0].replace(/([A-Z])/g, ' $1').trim().replaceAll(" ", "-").toLowerCase() + ": " + value);
}
}
for (var i = 0; i < calculatedProperties.length; i++) {
for (var a = 0; a < Arguments.length; a++) {
if (calculatedProperties[i].includes(Arguments[a])) {
window.splitted = calculatedProperties[i].split("");
window.joinThis = [];
for (var k = 0; k < splitted.indexOf(":"); k++) {
joinThis.push(splitted[k]);
};
if (joinThis.join("") == Arguments[a]) {
matchedProperties.push(calculatedProperties[i]);
}
}
}
}
if (tellInConsole !== undefined && tellInConsole == true) {
console.warn("StyleOf() Calculations Completed You Can Now Use Console.")
}
return matchedProperties
}
The TreeWalker object is designed to quickly parse DOM nodes in a document. If you expand on the example given above in the MDN Web Docs you can output the computed CSS properties for a given node.
The first property of the method is the node you want to traverse – in this case it's document.body:
var treeWalker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_ELEMENT,
{ acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } },
false
);
var nodeList = [];
var currentNode = treeWalker.currentNode;
while(currentNode) {
nodeList.push(currentNode);
const style = getComputedStyle(currentNode)
console.log(style)
currentNode = treeWalker.nextNode();
console.log("moving to next node...");
}
Welp #kaiido answered the question.
function styleOf(element, properties) {
const computed = getComputedStyle(element);
return properties.map( key => key + ": " + computed[ key ] )};
var style = styleOf(document.getElementsByTagName("body")[0], ["height", "width", "background-color", "font-size", "color", "font-family"]);
console.log(style);

Recursion to traverse all the nested child nodes of Binary Tree Javascript

I am playing around with a binary tree. I am trying to use recursion to find all the nested children's values and push all the values into an array. I started with the left tree to see if it works. I tried to call childrenArray() but the console says childrenArray() is not defined. When I ask if (typeof BinaryTree.prototype.childrenArray === 'function'), it returns true. Please teach me and tell me why I wasn't able to execute my code?
var Tree = function(value) {
if (!(this instanceof Tree)) {
return new Tree(value);
}
this.value = value;
this.children = [];
};
Tree.prototype.addChild = function(value) {
var child = new Tree(value);
this.children.push(child);
};
Tree.prototype.contains = function(value) {
if (this.value === value) {
return true;
} else {
for (var i = 0; i < this.children.length; i++) {
if (this.children[i] && this.children[i].contains(value)) {
return true;
}
}
return false;
}
};
var BinaryTree = function(value) {
if (!(this instanceof BinaryTree)) {
return new BinaryTree(value);
}
Tree.call(this, value);
};
BinaryTree.prototype = Object.create(Tree.prototype);
BinaryTree.prototype.addChild = function(value) {
if (value < this.value) {
if (this.children[0] === undefined) {
this.children[0] = new BinaryTree(value);
}
this.children[0].addChild(value);
} else if (value > this.value) {
if (this.children[1] === undefined) {
this.children[1] = new BinaryTree(value);
}
this.children[1].addChild(value);
}
};
BinaryTree.prototype.contains = function(value) {
if (value < this.value) {
if (this.children[0] === undefined) {
return false;
}
return this.children[0].contains(value);
} else if (value > this.value) {
if (this.children[1] === undefined) {
return false;
}
return this.children[1].contains(value);
}
};
var a = new BinaryTree();
a.value = 10;
a.addChild(4);
a.addChild(11);
a.addChild(3);
BinaryTree.prototype.childrenArray = function() {
var results = [];
if (this.value) {
results.push(this.value);
}
if (this.children[0].length === 0) {
return results;
}
for (var i = 0; i < this.children[0].children.length; i++) {
if (this.children[i].value) {
results.push(this.children[i].value);
return this.childrenArray();
}
}
};
a.childrenArray();
As #melpomene mentioned, you are invoking childArray but you didn't define it anywhere. I assume the line return childArray(); ended up there by mistake, you probably meant to recursively return childrenArray for the left child of root.
I would like to mention that your loop itself (without the recursive call):
for(var i = 0; i < this.children[0].children.length; i++) { // <-- you are iterating over the children of root's left child
if(this.children[i].value) { // <-- but you are accessing root's current child
results.push(this.children[i].value);
}
}
is somewhat confusing. You are iterating over the children of root's left child children[0].children, but on each iteration you check if the root's children themselves children[i] have a value and you push that value.
This is incorrect and will break if, for example, the root only has a left child that has both children (i will be out of bounds).
Here's how you can approach this problem. The recursion to print the left tree in your case can be broken down into the following cases:
If the current node has no value, return an empty array
Else If the current node has no children, return an array only containing the current value
Else if the current node has a left child, run childrenArray on it recursively and add the results to the results array
Here's how that would look:
BinaryTree.prototype.childrenArray = function() {
var results = [];
// case 1:
if (this.value === undefined) {
return results;
}
// case 2:
results.push(this.value);
if (this.children.length === 0) {
return results;
}
// case 3:
var leftChild = this.children[0];
if (leftChild) {
results = results.concat(leftChild.childrenArray());
}
/* add code here for the right child to complete your function */
return results;
};
Full Example:
var BinaryTree = function(value) {
this.value = value;
this.children = [];
};
BinaryTree.prototype.addChild = function (value) {
if (value < this.value) {
if (this.children[0] === undefined) {
this.children[0] = new BinaryTree(value);
}
this.children[0].addChild(value);
} else if (value > this.value) {
if (this.children[1] === undefined) {
this.children[1] = new BinaryTree(value);
}
this.children[1].addChild(value);
}
};
BinaryTree.prototype.childrenArray = function() {
var results = [];
// case 1:
if (this.value === undefined) {
return results;
}
// case 2:
results.push(this.value);
if (this.children.length === 0) {
return results;
}
// case 3:
var leftChild = this.children[0];
if (leftChild) {
results = results.concat(leftChild.childrenArray());
}
/* add code here for the right child to complete your function */
return results;
};
var a = new BinaryTree(10);
a.addChild(4);
a.addChild(11);
a.addChild(3);
console.log(a.childrenArray()); // [10, 4, 3]
Last thing, based on your insertion logic (insert left if smaller, right if larger), you are building a Binary Search Tree not a Binary Tree. Binary tree's don't follow any particular insertion logic. Take a look at this question for clarification

accessing a property of a node, javascript binary search tree

I'm new to nodeJS javascript and I have a simple problem here.
I have a Binary Search Tree (BST) in javascript. Each Node has a value, and a count. We're inserting words into the BST such that each Node represents a word. Upon insertion, if the word is already in the BST, we want to increase the count of that word, where count is a property on the Node.
My problem comes when I want to display the Nodes and their counts. Displaying the counts is not working correctly. That is, the BST.prototype.showWords = function (node) is not correct.
Thank you for your help and insight!!!
files:
bstnode.js - the 'node class'
BST.js - the Binary Search Tree Class
wordCount.js - reads in a text file, splits on spaces to get words, and creates nodes. I want each node to represent a word, and if that word appears multiple times, count++ on that node each time.
// wordCount.js
var BST = require('./bst.js');
var fs = require('fs');
var countNodes = require('./countNodes.js');
// THIS RIGHT HERE DOES NOT WORK CORRECTLY.
BST.prototype.showWords = function (node) {
if (node !== null) {
this.inOrder(node.left);
console.log(node.showCount());
this.inOrder(node.right);
}
};
// get the file, and get it into an array of string-words
var filePath = './simpleTest.txt';
var contents = fs.readFileSync(filePath).toString();
var stringArr = contents.split(' ');
var myBST = new BST();
for (var i=0; i<stringArr.length; i++){
var word = stringArr[i].trim();
var aNode = myBST.find(word);
console.log(aNode);
if ( aNode !== null ) { // then word exists in BST already,
aNode.count++; // node count ++ on that one
}
else { // then word dne in BST, so add it now!
myBST.insert(word);
}
}
myBST.showWords(myBST.root);
// bstnode.js
'use strict';
var Node = function (data, left, right) {
this.data = data;
this.count = 1;
this.left = left;
this.right = right;
};
Node.prototype.show = function () {
return this.data;
};
Node.prototype.show2 = function () {
return (this.data + ' ' + this.count);
};
module.exports = Node;
'use strict';
// bst.js - has the BST CTor function, and requires the bstnode in
var Node = require('./bstnode');
// BST CTor function
var BST = function() { // Binary Search Tree class
this.root = null;
};
BST.prototype.insert = function (data) {
var n = new Node(data, null, null);
if (this.root === null) {
this.root = n;
} else {
var current = this.root;
var parent;
while (true) {
parent = current;
if (data < current.data) {
current = current.left;
if (current === null) {
parent.left = n;
break;
}
} else {
current = current.right;
if (current === null) {
parent.right = n;
break;
}
}
}
}
};
// inOrder: log VALUES in order starting from node param
BST.prototype.inOrder = function (node) {
if (node !== null) {
this.inOrder(node.left);
console.log(node.show() + " ");
this.inOrder(node.right);
}
};
BST.prototype.find = function (data) {
var current = this.root;
while (current && current.data !== data) {
if (data < current.data) {
current = current.left;
} else {
current = current.right;
}
}
return current;
};
module.exports = BST;
a friend helped me out, here's the soln
// THIS RIGHT HERE -- - --
// That's because it should call itself recursively, not the inOrder function!
BST.prototype.showWords = function (node) {
if (node !== null) {
this.showWords(node.left);
console.log(node.showCount());
this.showWords(node.right);
}
};

convert xml to json in Javascript

I have the following javascript function (which I got from Stack Overflow) which converts XML to JSON:
function xmlToJson(xml) {
try {
var obj = {};
if (xml.nodeType == 1) {
if (xml.attributes.length > 0) {
for (var j = 0; j < xml.attributes.length; j++) {
var attribute = xml.attributes.item(j);
obj[attribute.nodeName] = attribute.nodeValue;
}
}
} else if (xml.nodeType == 3) {
obj = xml.nodeValue;
}
if (xml.hasChildNodes()) {
for (var i = 0; i < xml.childNodes.length; i++) {
var item = xml.childNodes.item(i);
var nodeName = item.nodeName;
if (typeof (obj[nodeName]) == "undefined") {
obj[nodeName] = xmlToJson(item);
} else {
if (typeof (obj[nodeName].push) == "undefined") {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xmlToJson(item));
}
}
}
console.log(JSON.stringify(obj));
return obj;
} catch (e) {
alert(e.message);
}
}
What I want is to return it as an array ([]) when a xml node has at-least single child node and it has a parent node also. In this code it returns map ({}) if xml node has single child node but it is fine with multiple child nodes.
For example, I'd like the XML
<pnode attr1="abc">
<cnode attr2="xyz"></cnode>
</pnode>
to be transformed into the JSON
{
"pnode": {
"attr1": "abc"
},
"cnode": [
{"attr2": "xyz"}
]
}
With the clarification about what you want to achieve, here is an algorithm.
I'll leave my other answer up because I still think the wisest choice is not to play with the structure
function flattenNodes(node, isChild) {
var obj = {}, obj2, i, key, attributes = {};
if (node.attributes && node.attributes.length)
for (i = 0; i < node.attributes.length; ++i)
attributes[node.attributes[i].nodeName] = node.attributes[i].nodeValue;
if (!isChild)
obj[node.nodeName] = attributes;
else {
if (!obj.hasOwnProperty(node.nodeName))
obj[node.nodeName] = [];
else if (!(obj[node.nodeName] instanceof Array))
obj[node.nodeName] = [obj[node.nodeName]];
obj[node.nodeName].push(attributes);
}
attributes = null; // free
if (node.childNodes && node.childNodes.length)
for (i = 0; i < node.childNodes.length; ++i) {
if (node.childNodes[i].nodeType === 3) continue; // skip text node
obj2 = flattenNodes(node.childNodes[i], 1); // recurse
for (key in obj2) // merge
if (obj2.hasOwnProperty(key))
if (!obj.hasOwnProperty(key)) {
obj[key] = obj2[key];
} else {
if (!(obj[key] instanceof Array))
obj[key] = [obj[key]];
obj[key] = obj[key].concat(obj2[key]);
}
}
return obj;
}
Example usage on Node root_node
var root_node;
root_node = new DOMParser().parseFromString(
'<pnode attr1="abc"><cnode attr2="xyz"></cnode></pnode>',
'text/xml'
).documentElement;
var o = flattenNodes(root_node); // create
JSON.stringify(o); // to JSON
// {"pnode":{"attr1":"abc"},"cnode":[{"attr2":"xyz"}]}
If you have XML of the form <foo bar="baz"><foo hello="world"></foo></foo>, the first iteration will cause {foo: {bar: "baz"}}, then the second encounter will modify this to the array form of {foo: [{bar: "baz"}, {hello: "world"}]}
I would form the object representing the XML differently;
Integer nodeType
String nodeName
String nodeValue
Array childNodes
Object attributes
Now you can have the same form independent of number of child nodes/etc
function nodeToObject(node) {
var obj = {}, i;
obj.nodeType = node.nodeType;
obj.nodeName = node.nodeName;
obj.nodeValue = node.nodeValue;
obj.childNodes = [];
obj.attributes = {};
if (node.childNodes && node.childNodes.length)
for (i = 0; i < node.childNodes.length; ++i)
obj.childNodes.push(nodeToObject(node.childNodes[i]));
if (node.attributes && node.attributes.length)
for (i = 0; i < node.attributes.length; ++i)
obj.attributes[node.attributes[i].nodeName] = node.attributes[i].nodeValue;
return obj;
}
And then to transform root_node to JSON,
JSON.stringify(nodeToObject(root_node));
Going in the opposite direction is also possible in JavaScript, with some minor logic based upon nodeType to choose the creation method.

Trees Structure - Javascript - Parents?

Simply put
I have a tree structure made of objects.
Is it possible to build that tree and add to each object a reference to their parent ?
I know referencing works with objects, but i'm not sure if it would in that case?
I would like to be able to write something like this
currentLevel = this.getParent();
another exemple would be
this.getChildList().addChild({name: test,parent: this})
Without having copies and creating multiple tree from the first one.
2nd question
How would referencing works with array? Are they considered objects or does it depends on their content?
3nd question
Would saving the tree in the browser's cache, via string-JSON serialisation destroy the references?
You can do this be creating a "TreeNode" class:
var TreeNode = (function(){
//keep track of parent node
TreeNode.prototype.parent = null;
//keep track of children
TreeNode.prototype.children = [];
function TreeNode(parent) {
if(parent !== undefined) {
if(this.setParent(parent)) {
this.parent.addChild(this);
}
}
//...
}
TreeNode.prototype.setParent = function(parent) {
//add some sort of check to make sure it is a `TreeNode`
if(parent instanceof TreeNode) {
this.parent = parent;
return true;
}
return false;
}
TreeNode.prototype.addChild = function(child) {
//add some sort of check to make sure it is a `TreeNode`
if(child instanceof TreeNode) {
this.children.push(child);
child.setParent(this);
}
}
TreeNode.prototype.getParent = function(){
return this.parent;
}
TreeNode.prototype.getChildren = function(){
return this.children;
}
return TreeNode;
})();
And then you can expand from that.
Example Code:
var node_a = new TreeNode();
var node_b = new TreeNode(node_a);
var node_c = new TreeNode(node_a);
console.log(node_a.getParent(), node_c.get_parent()); //null , node_a
console.log(node_a.getChildren()); //[node_b, node_c]
This is just a start, it needs waaaaaaaaaay more expansion :-)
Okay, so there are most likely frameworks out there, but I wrote a quick thing which supports JSON serialisation and the reverse (via it's own methods). I took base inspiration from Neal's answer. Example
var a = new MyTreeNode('a'), // make some nodes
b = new MyTreeNode('b'),
c = new MyTreeNode('c');
a.addChild(b).addChild(c); // a parent of b parent of c
c.getParent() === b; // true
var str = a.toJSON(); // "{"nodeName":"a","childNodes":[{"nodeName":"b","childNodes":[{"nodeName":"c","childNodes":[]}]}]}"
MyTreeNode.parseJSON(str); // MyTreeNode (same structure as before)
Full code
/* MyTreeNode(String nodeName)
Instance Properties
- nodeName, String
- childNodes, Array of MyTreeNodes
- parentNode, MyTreeNode
Instance Methods
- addChild(MyTreeNode node), child MyTreeNode
- removeChild(MyTreeNode node), child MyTreeNode
- getParent, parent MyTreeNode
- getChildList, Array of MyTreeNodes
- serialise, JSON-safe Object
- toJSON, String
Constructor Methods
- deserialise(Object serialised), MyTreeNode
- parseJSON(String JSONString), MyTreeNode
*/
var MyTreeNode = (function () {
function MyTreeNode(nodeName) {
nodeName && (this.nodeName = nodeName);
this.childNodes = [];
}
MyTreeNode.prototype.parentNode = null;
MyTreeNode.prototype.childNodes = [];
MyTreeNode.prototype.nodeName = '';
// getters
MyTreeNode.prototype.getChildList = function () {
return this.childNodes = [];
};
MyTreeNode.prototype.getParent = function () {
return this.parentNode;
};
// add/remove
MyTreeNode.prototype.removeChild = function (node) {
var i = this.childNodes.indexOf(node);
if (node.parentNode !== this || i == -1)
throw new ReferenceError('node is not a child of this');
this.childNodes.splice(i, 1);
node.parentNode = null;
return node;
};
MyTreeNode.prototype.addChild = function (node) {
if (node.parentNode) node.parentNode.removeChild(node);
node.parentNode = this;
this.childNodes.push(node);
return node;
};
// JSON
MyTreeNode.prototype.serialise = function () {
var o = {
nodeName: this.nodeName,
childNodes: []
}, i;
for (i = 0; i < this.childNodes.length; ++i) {
o.childNodes.push(this.childNodes[i].serialise());
}
return o;
};
MyTreeNode.prototype.toJSON = function () {
return JSON.stringify(this.serialise());
};
MyTreeNode.deserialise = function (o) {
var p = new MyTreeNode(o.nodeName), i;
for (i = 0; i < o.childNodes.length; ++i) {
p.addChild(MyTreeNode.deserialise(o.childNodes[i]));
}
return p;
};
MyTreeNode.parseJSON = function (str) {
var o = JSON.parse(str);
return MyTreeNode.deserialise(o);
};
return MyTreeNode;
}());
You could traverse your object and add parent properties to every subobject:
function addParents(obj) {
var name;
for (name in obj) {
if (typeof obj[name] === "object") {
addParents(obj[name]);
obj[name].parent = obj;
}
}
}
var obj = {
g: {
k: [
{
r : 1
},
{
r : 1
}
],
j: {
h: 1
}
}
};
addParents(obj);
console.log(obj.g.parent === obj); //true
console.log(obj.g.k.parent === obj.g); //true
console.log(obj.g.k[1].parent === obj.g.k); //true
console.log(obj.g.j.parent === obj.g); //true
And if you want to add objects later on, you could use something like this:
function addChild(obj, child, name){
obj[name] = child;
child.parent = obj;
}
addChild(obj.g, {t:1}, "xy");
console.log(obj.g.xy.parent === obj.g); //true
FIDDLE

Categories