Skip to content

Instantly share code, notes, and snippets.

@msafadieh
Last active September 23, 2019 00:55
Show Gist options
  • Save msafadieh/d2941317065a5a210d81ff13a958c589 to your computer and use it in GitHub Desktop.
Save msafadieh/d2941317065a5a210d81ff13a958c589 to your computer and use it in GitHub Desktop.
find shortest path from one wiki page to the other
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