(JavaScript) 创建一种比我拥有的算法更高效的算法

我有这种情况:


    let scans = [

      { source: "10.0.0.2", destination: "20.0.0.2" }

      { source: "10.0.0.4", destination: "20.0.0.6" }

    ]


    const handleScan = (source, destination, port) => {

      let newScan = {

        source : source, 

        destination : destination

      }


      for (scan of scans) {

        if (scan.source !== source && scan.destination !== destination)

        scans.push(newScan)

      }

    }

现在,该函数每秒执行 1000 次,这意味着每次查看该对是否存在的 for 循环非常糟糕。你会建议我如何更有效地做到这一点?


Qyouu
浏览 160回答 1
1回答

烙印99

目标是跟踪所有来源的所有目的地吗?如果是这样,那就不是它目前正在做的事情。以下是如何做到这一点:let scans = [  { source: "10.0.0.2", destination: "20.0.0.2" }  { source: "10.0.0.4", destination: "20.0.0.6" }]const handleScan = (source, destination, port) => {  let newScan = {    source : source,     destination : destination  }  var scanFound = false;  for (scan of scans) {    if (scan.source !== source && scan.destination !== destination){      scanFound = true;      break;    }  }  if(!scanFound){    scans.push(newScan)  }}如果这是目标,我建议将格式更改为以 source 为键、destinations 为值的对象,因此它是查找而不是循环:var destinationsBySource = {  "10.0.0.2": ["20.0.0.2"],  "10.0.0.4": ["20.0.0.6"]]var handleScan = function(source, destination){  //Initialize destinations as an array if source is not there  destinationsBySource[source] = destinationsBySource[source] || [];  //Add the destination if needed  if(destinationsBySource[source].indexOf(destination) == -1){    destinationsBySource[source].push(destination);  }};//End of handleScan function
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript