【问题标题】:Eloquent Javavascript, Chapter 11 (Asynchronous Programming), Question on path finding algorithmEloquent Javascript,第 11 章(异步编程),寻路算法问题
【发布时间】:2021-04-11 11:53:02
【问题描述】:

我在理解 Eloquent Javascript 电子书Chapter 11(消息路由部分)中的一行代码时遇到问题。在其中,作者试图解释假定网络中的消息路由如何工作(通过结合 Promise 和其他异步概念)。他构建了不同类型的函数来处理不同的操作(发送请求、接收请求、响应......)。但是还有这个寻路算法的实现,我觉得我不是很懂。

//SECTION THAT CREATES A KIND OF NEIGHBOUR MAP THAT EVERY NEST (COMPUTER) HAS 

requestType("connections", (nest, {name, neighbors},
                            source) => {
  let connections = nest.state.connections;
  if (JSON.stringify(connections.get(name)) ==
      JSON.stringify(neighbors)) return;
  connections.set(name, neighbors);
  broadcastConnections(nest, name, source);
});

function broadcastConnections(nest, name, exceptFor = null) {
  for (let neighbor of nest.neighbors) {
    if (neighbor == exceptFor) continue;
    request(nest, neighbor, "connections", {
      name,
      neighbors: nest.state.connections.get(name)
    });
  }
}

everywhere(nest => {
  nest.state.connections = new Map();
  nest.state.connections.set(nest.name, nest.neighbors);
  broadcastConnections(nest, nest.name);
});

//PATH FINDING FUNCTION
function findRoute(from, to, connections) {
  let work = [{at: from, via: null}];
  for (let i = 0; i < work.length; i++) {
    let {at, via} = work[i];
    for (let next of connections.get(at) || []) {
      if (next == to) return via;
      if (!work.some(w => w.at == next)) {
        work.push({at: next, via: via || next});
      }
    }
  }
  return null;
}

//THEN THERE ARE FUNCTIONS THAT HANDLE THE ACTUAL MESSAGE SENDING/ROUTING

function routeRequest(nest, target, type, content) {
  if (nest.neighbors.includes(target)) {
    return request(nest, target, type, content);
  } else {
    let via = findRoute(nest.name, target,
                        nest.state.connections);
    if (!via) throw new Error(`No route to ${target}`);
    return request(nest, via, "route",
                   {target, type, content});
  }
}

requestType("route", (nest, {target, type, content}) => {
  return routeRequest(nest, target, type, content);
});

我的问题是,在 findRoute 函数中,为什么会有 || [] 在内部 for 循环中?是否存在适当的后续错误处理(以防万一在连接属性中没有指定为具有邻居的嵌套,但不管列为某人的邻居嵌套)?

【问题讨论】:

  • connections.get(at) 可能返回 null 或 undefined,具体取决于 api,并且您不能在 null 或 undefined 上执行 for...of 循环,因此在这种情况下他会将该值替换为空数组
  • 感谢您的回复,对您有帮助:)

标签: javascript asynchronous routes dijkstra


【解决方案1】:

connections.get(at) 可能返回 null 或 undefined,具体取决于 api,并且您不能对 null 或 undefined 执行 for...of 循环,因此在这种情况下他会将该值替换为空数组

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    • 1970-01-01
    • 2015-09-09
    • 1970-01-01
    相关资源
    最近更新 更多