Skip to content

Instantly share code, notes, and snippets.

@tomasevich
Created April 23, 2026 20:03
Show Gist options
  • Select an option

  • Save tomasevich/355b0bd5093841e740945303f1f05c13 to your computer and use it in GitHub Desktop.

Select an option

Save tomasevich/355b0bd5093841e740945303f1f05c13 to your computer and use it in GitHub Desktop.
Интересная задачка JavaScript с рекурсивной функцией

Tip

Задача: Собери весь маршрут от точки А к точке Б с учетом данных о полетах

const input = [
  { from: 'Moscow', to: 'London' },
  { from: 'Paris', to: 'Shanhai' },
  { from: 'New York', to: 'Astana' }
]

const output = [
  { from: 'London', to: 'Paris' },
  { from: 'Shanhai', to: 'New York' },
  { from: 'Astana', to: 'Moscow' }
]

Warning

Решение через рекурсию, но это чревато переполнением стэка

// Объединим все сегменты в один список для удобного поиска
const allSegments = [...input, ...output]

function getHistory(from, target, history = []) {
  // Ищем сегмент, который начинается с текущей точки
  const segment = allSegments.find(way => way.from === from)

  if (!segment) return history // Предохранитель, если путь прерван

  history.push(segment)

  // Если приехали в конечную точку (Moscow), возвращаем результат
  if (segment.to === target) return history

  // Рекурсия: идем дальше от точки segment.to
  return getHistory(segment.to, target, history)
}

console.log(getHistory('Moscow', 'Moscow'))

Important

Использование цикла while — отличное решение для работы с потенциально длинными цепочками данных

function getHistory(startPoint, endPoint) {
  const allSegments = [...input, ...output]
  const history = []
  let currentCity = startPoint

  // Цикл продолжается, пока мы не дошли до цели
  // Добавлена проверка на наличие сегмента, чтобы избежать бесконечного цикла
  while (true) {
    const segment = allSegments.find(way => way.from === currentCity)

    if (!segment) break // Если путь обрывается, выходим

    history.push(segment)
    currentCity = segment.to

    if (currentCity === endPoint) break // Цель достигнута

    // Предохранитель от бесконечного цикла (на случай, если Москва не конечная)
    if (history.length > allSegments.length) break
  }

  return history
}

console.log(getHistory('Moscow', 'Moscow'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment