Last active
September 23, 2019 00:55
-
-
Save msafadieh/d2941317065a5a210d81ff13a958c589 to your computer and use it in GitHub Desktop.
find shortest path from one wiki page to the other
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios from 'axios' | |
export async function findShortestPath(firstPage, secondPage, callback, parent) { | |
if (state === undefined) { | |
state = {} | |
state.done = false; | |
state.visited = {} | |
state.visited[firstPage] = true; | |
} | |
if (state.done) return; | |
console.log("Checking ${firstPage}") | |
const page = { | |
'page': firstPage, | |
'parent': parent | |
}; | |
if (firstPage === secondPage) { | |
state.done = true; | |
callback(page); | |
} | |
await axios.get('https://en.wikipedia.org/wiki/' + firstPage) | |
.then(response => { | |
let domParser = new DOMParser(); | |
let htmlDoc = domParser.parseFromString(response.data, 'text/html'); | |
let urls = htmlDoc.getElementById('bodyContent') | |
.innerHTML | |
.match(/\/wiki\/(?!(?:Talk|Wikipedia|User|Template|Template_talk|Category|Help|File|Special):)([^#"]+)/g); | |
urls.forEach(url => { | |
if (!state.visited[url]) { | |
state.visited[url] = true; | |
findShortestPath(url, secondPage, callback, page); | |
} | |
}) | |
}) | |
.catch(() => that.message = "An error has occurred.") | |
} | |
function printAll(page) { | |
return page.parent ? printAll(page.parent) + " --> " + page.page : page.page; | |
} | |
findShortestPath("Lebanon", "Panda", printAll); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment