Breadth first search не срабатывает return

Я не понимаю, почему не срабатывает оператор return на 78 строке

class Graph {
  constructor() {
    this.nodes = [];
    this.edges = [];
  }

  addNode(value) {
    this.nodes.push({
      value: value,
      visit: false,
      lines: []
    });
  }

  find(value) {
    return this.nodes.find(node => {
      return node.value === value;
    });
  }

  addLine(valueA, valueB) {
    var nodeA = this.find(valueA);
    var nodeB = this.find(valueB);

    if (!nodeA) {
      this.addNode(valueA);
      nodeA = this.find(valueA);
    }

    if (!nodeB) {
      this.addNode(valueB);
      nodeB = this.find(valueB);
    }

    nodeA.lines.push(nodeB);
    nodeB.lines.push(nodeA);
  }

  setVisit(node, bool) {
    node.visit = bool;
  }

  getVisit(node) {
    return node.visit;
  }
}

function clone(array) {
  var copy = [];

  array.forEach(element => {
    copy.push(element);
  });

  return copy;
}

function breadthFirstSearch(start) {
  var chains = {},
    queueValuesToExplore = [start.value];

  width.setVisit(start, true);
  var step = [];
  step.push(start.value);
  chains[start.value] = step;

  while (queueValuesToExplore.length > 0) {
    let current = queueValuesToExplore.shift();
    let neighbors = width.find(current).lines;
    let step = chains[current];
    delete chains[current];
    neighbors.forEach(childItem => {
      if (childItem === finish) {
        let cloneStep = clone(step);
        cloneStep.push(childItem.value);
        chains[childItem.value] = cloneStep;
        console.log('RETURN ', chains[childItem.value]);
        return chains[childItem.value];
      } else {
        if (!width.getVisit(childItem)) {
          let cloneStep = clone(step);
          width.setVisit(childItem, true);
          queueValuesToExplore.push(childItem.value);
          cloneStep.push(childItem.value);
          chains[childItem.value] = cloneStep;
        }
      }
    });
  }

  return null;
}

var width = new Graph();
width.addLine("a", "b");
width.addLine("a", "c");
width.addLine("b", "e");

var start = width.find("a"),
  finish = width.find("e");

var result = breadthFirstSearch(start);
console.log(result);

А где нумерация строк?

77 строка выводит на консоль (зри скриншот), а 78 строка return не выполняет, но продолжает цикл… чудеса

Не понятно про какие номера строк ты говоришь) У тебя функция в конечном итоге возращает null. Он собсно и логируется в конце.

Думаю в той 78 строке return все же выполняется. И кажется мне, что тот return это вывод из анонимной функции в методе forEach, и цикл будет продожаться до тех пор, пока будет истино условие вначале

2 лайка

Красава! Вот оно в чем проблема.

Именно в этом дело

1 лайк

Все логично. Return всегда является возвратом из функции, в вашем случае корректно отрабатывает console.log(‘RETURN’); после чего идет след. итерация в методе forEach так как там вы используется анонимную функцию =>, вот как пример:

var array1 = ['a', 'b', 'c'];
array1.forEach(function(element) {
  console.log(element);
  return;
});

После всех итераций в методе forEach, отрабатывает ваш while цикл и в конце метода возвращается return null;

Если ваша цель вернуть из метода return chains[childItem.value]; то сохраните его в переменную и потом выведите в конце:

var result = null;
...
console.log('RETURN ', chains[childItem.value]);
result = chains[childItem.value];
...
return result;
2 лайка

result = chains[childItem.value];
return;
после while (queueValuesToExplore.length > 0 && result === undefined) {…}
return result;
Так возвращает значение.