From 06ce63eb42bd9d9a0583e7087bee260c0c16e4ec Mon Sep 17 00:00:00 2001 From: Alex de Mulder Date: Fri, 17 Apr 2015 10:57:21 +0200 Subject: [PATCH] removed duplicate code --- .../components/physics/BarnesHutSolver.js | 49 ++++++++++--------- 1 file changed, 27 insertions(+), 22 deletions(-) diff --git a/lib/network/modules/components/physics/BarnesHutSolver.js b/lib/network/modules/components/physics/BarnesHutSolver.js index a77ce758..879a7b86 100644 --- a/lib/network/modules/components/physics/BarnesHutSolver.js +++ b/lib/network/modules/components/physics/BarnesHutSolver.js @@ -72,17 +72,7 @@ class BarnesHutSolver { // original condition : s/d < theta = passed === d/s > 1/theta = passed // calcSize = 1/s --> d * 1/s > 1/theta = passed if (distance * parentBranch.calcSize > this.thetaInversed) { - // duplicate code to reduce function calls to speed up program - if (distance === 0) { - distance = 0.1 * Math.random(); - dx = distance; - } - var gravityForce = this.options.gravitationalConstant * parentBranch.mass * node.options.mass / (distance * distance * distance); - var fx = dx * gravityForce; - var fy = dy * gravityForce; - - this.physicsBody.forces[node.id].x += fx; - this.physicsBody.forces[node.id].y += fy; + this._calculateForces(distance, dx, dy, node, parentBranch); } else { // Did not pass the condition, go into children if available @@ -94,17 +84,7 @@ class BarnesHutSolver { } else { // parentBranch must have only one node, if it was empty we wouldnt be here if (parentBranch.children.data.id != node.id) { // if it is not self - // duplicate code to reduce function calls to speed up program - if (distance === 0) { - distance = 0.5 * Math.random(); - dx = distance; - } - var gravityForce = this.options.gravitationalConstant * parentBranch.mass * node.options.mass / (distance * distance * distance); - var fx = dx * gravityForce; - var fy = dy * gravityForce; - - this.physicsBody.forces[node.id].x += fx; - this.physicsBody.forces[node.id].y += fy; + this._calculateForces(distance, dx, dy, node, parentBranch); } } } @@ -112,6 +92,31 @@ class BarnesHutSolver { } + /** + * Calculate the forces based on the distance. + * + * @param distance + * @param dx + * @param dy + * @param node + * @param parentBranch + * @private + */ + _calculateForces(distance, dx, dy, node, parentBranch) { + // duplicate code to reduce function calls to speed up program + if (distance === 0) { + distance = 0.1 * Math.random(); + dx = distance; + } + var gravityForce = this.options.gravitationalConstant * parentBranch.mass * node.options.mass / (distance * distance * distance); + var fx = dx * gravityForce; + var fy = dy * gravityForce; + + this.physicsBody.forces[node.id].x += fx; + this.physicsBody.forces[node.id].y += fy; + } + + /** * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes. *