(JavaScript) 创建一个比我的算法更有效的算法

(JavaScript) Creating a more efficient algorithm than the one I had

我有这种情况:

    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 循环来查看是否存在对是非常糟糕的。 你会建议我如何更有效地做到这一点?

目标是跟踪所有来源的所有目的地吗?如果是这样,那不是它目前正在做的事情。方法如下:

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)
  }
}

如果这是目标,我建议将格式更改为以源为键、以目标为值的对象,这样它就是查找而不是循环:

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