From 4b0499f2e0956146fbbfb6797dd8748b2c46b828 Mon Sep 17 00:00:00 2001 From: Felipe Ribeiro Date: Sun, 3 Aug 2014 16:57:59 +0200 Subject: [PATCH] Remove function declaration from loop --- algorithms/graph/breadth_first_search.js | 21 ++++++++++----------- algorithms/graph/prim.js | 18 +++++++++--------- 2 files changed, 19 insertions(+), 20 deletions(-) diff --git a/algorithms/graph/breadth_first_search.js b/algorithms/graph/breadth_first_search.js index 6278c84..51ea946 100644 --- a/algorithms/graph/breadth_first_search.js +++ b/algorithms/graph/breadth_first_search.js @@ -65,19 +65,18 @@ var breadthFirstSearch = function (graph, startVertex, callbacks) { vertexQueue.push(startVertex); callbacks = normalizeCallbacks(callbacks, [startVertex]); - /* jshint loopfunc: true */ - while (!vertexQueue.isEmpty()) { - var vertex = vertexQueue.pop(); + var vertex; + var enqueue = function (neighbor) { + if (callbacks.allowTraversal(vertex, neighbor)) { + callbacks.onTraversal(vertex, neighbor); + vertexQueue.push(neighbor); + } + }; + while (!vertexQueue.isEmpty()) { + vertex = vertexQueue.pop(); callbacks.enterVertex(vertex); - - graph.neighbors(vertex).forEach(function (neighbor) { - if (callbacks.allowTraversal(vertex, neighbor)) { - callbacks.onTraversal(vertex, neighbor); - vertexQueue.push(neighbor); - } - }); - + graph.neighbors(vertex).forEach(enqueue); callbacks.leaveVertex(vertex); } }; diff --git a/algorithms/graph/prim.js b/algorithms/graph/prim.js index b7a0e35..603f490 100644 --- a/algorithms/graph/prim.js +++ b/algorithms/graph/prim.js @@ -25,7 +25,14 @@ var prim = function (graph) { q.insert(vertex, Infinity); }); - /* jshint loopfunc: true */ + var relax = function (neighbor) { + var weight = graph.edge(vertex, neighbor); + if (weight < q.priority(neighbor)) { + q.changePriority(neighbor, weight); + parent[neighbor] = vertex; + } + }; + while (!q.isEmpty()) { var top = q.extract(true); var vertex = top.item, @@ -38,14 +45,7 @@ var prim = function (graph) { mst.addVertex(vertex); } - // Relax. - graph.neighbors(vertex).forEach(function (neighbor) { - var weight = graph.edge(vertex, neighbor); - if (weight < q.priority(neighbor)) { - q.changePriority(neighbor, weight); - parent[neighbor] = vertex; - } - }); + graph.neighbors(vertex).forEach(relax); } return mst;