Q:

barnes hut tree endlessly looping between insert and internalInsert

I'm trying to implement this data structure, a Barnes-Hut Octree, and I keep running into an endless loop, terminated by an out of memory exception.  
The complete fiddle is here: http://jsfiddle.net/cWvex/
but the functions I'm looping between are these:
OctreeNode.prototype.insert = function (body) {

    console.log('insert');

    if(this.isInternal){

        this.internalInsert(body);

        return;
    }

    if(this.isExternal){

        // insert the body into the spec.  quadrant, call internalUpdate
        for(var quadrant in this.internal.quadrants){
            if(this.internal.quadrants.hasOwnProperty(quadrant)){
                this.internal.quadrants[quadrant] = new OctreeNode();
            }
        }
        this.isExternal = false;
        this.isInternal = true;

        this.internalInsert(this.external);
        this.external = null;
        this.internalInsert(body);

        return;
    }

    if(this.isEmpty){

        this.external = body;
        this.isEmpty = false;
        this.isExternal = true;

        return;
    }

};

// Precondition: quadrants' nodes must be instantiated
OctreeNode.prototype.internalInsert = function(body) {

    console.log('internalInsert');

    this.internal.quadrants[this.quadrant(body)].insert(body);
    this.internalUpdate(body);

};

Anyone got an idea of what I'm missing? 

A:

I think the problem is to do with the quadrant function:
OctreeNode.prototype.quadrant = function (body) {

    console.log('quadrant');

    var pos = this.internal.pos;

    var quadrant = (body.pos.x < pos ? ' l' : 'r') + 
        (body.pos.y < pos ? ' u' : 'd') + 
        (body.pos.z < pos ? ' i' : 'o');

    return quadrant; 
};

The chosen quadrant should be based on the centre of the quadrant, not on the centre of mass.   I think you need to create a new variable to define the centre of the quadrant. 
Note that when you add nodes, the centre of mass (stored in pos) can change, but the centre of the quadrant remains fixed (otherwise things will go wrong when you descend into the octtree). 
At the moment, each new node is generated with a pos of 0,0,0 and so every point will always end up being assigned into the same quadrant of the node.   Therefore when you try to place two bodies into the tree, you end up with an infinite recursion:

Body 1 is inserted into node x
Body 2 is inserted into node x
Node 1 is split. 
Body 1 is inserted into quadrant 1 of node x
Body 2 is inserted into quadrant 1 of node x
Back to step 1 with x changed to the node at quadrant 1 of node x

EDIT
Incidentally, in the code that reads:
avgPos.x = (body.pos.x*body.mass + 
            avgPos.x * totalMass) / totalMass + body.mass

I think you need some more brackets to become
avgPos.x = (body.pos.x*body.mass + 
            avgPos.x * totalMass) / (totalMass + body.mass)

or the update of centre of mass will go wrong.