From a58b92c1233e7ed8d708bc0ef8f4744326e0aeb5 Mon Sep 17 00:00:00 2001 From: wimrijnders Date: Fri, 5 May 2017 08:29:08 +0200 Subject: [PATCH] Fix handling of node id's in saveAndLoad example (#2943) * Fix handling of node id's in saveAndLoad example * Code cleanup * Fixes for review --- examples/network/other/saveAndLoad.html | 42 +++++++++++++++---------- 1 file changed, 25 insertions(+), 17 deletions(-) diff --git a/examples/network/other/saveAndLoad.html b/examples/network/other/saveAndLoad.html index ee71b528..6f96df34 100644 --- a/examples/network/other/saveAndLoad.html +++ b/examples/network/other/saveAndLoad.html @@ -71,15 +71,6 @@ draw(); } - function addContextualInformation(elem, index, array) { - addId(elem, index); - addConnections(elem, index); - } - - function addId(elem, index) { - elem.id = index; - } - function addConnections(elem, index) { // need to replace this with a tree of the network, then get child direct children of the element elem.connections = network.getConnectedNodes(index); @@ -107,7 +98,7 @@ var nodes = objectToArray(network.getPositions()); - nodes.forEach(addContextualInformation); + nodes.forEach(addConnections); // pretty print node data var exportValue = JSON.stringify(nodes, undefined, 2); @@ -141,30 +132,47 @@ return new vis.DataSet(networkNodes); } + function getNodeById(data, id) { + for (var n = 0; n < data.length; n++) { + if (data[n].id == id) { // double equals since id can be numeric or string + return data[n]; + } + }; + + throw 'Can not find id \'' + id + '\' in data'; + } + function getEdgeData(data) { var networkEdges = []; - data.forEach(function(node, index, array) { + data.forEach(function(node) { // add the connection node.connections.forEach(function(connId, cIndex, conns) { networkEdges.push({from: node.id, to: connId}); + let cNode = getNodeById(data, connId); - var elementConnections = array[connId].connections; + var elementConnections = cNode.connections; // remove the connection from the other node to prevent duplicate connections var duplicateIndex = elementConnections.findIndex(function(connection) { - connection === node.id; + return connection == node.id; // double equals since id can be numeric or string }); - elementConnections = elementConnections.splice(0, duplicateIndex - 1).concat(elementConnections.splice(duplicateIndex + 1, elementConnections.length)) - }); + + if (duplicateIndex != -1) { + elementConnections.splice(duplicateIndex, 1); + }; + }); }); return new vis.DataSet(networkEdges); } function objectToArray(obj) { - return Object.keys(obj).map(function (key) { return obj[key]; }); + return Object.keys(obj).map(function (key) { + obj[key].id = key; + return obj[key]; + }); } function resizeExportArea() { @@ -174,4 +182,4 @@ init(); - \ No newline at end of file +