function splitPath(route) { route = route.split('/') if (route[0] === '') { route = route.slice(1) } if (route[route.length - 1] === '') { route = route.slice(0, route.length - 1) } return route } function matchRoute(route, path) { route = splitPath(route) path = splitPath(path) if (route.length != path.length) { return null } const result = {} for (let i = 0; i < route.length; i++) { const elem = route[i] if (elem.startsWith('{') && elem.endsWith('}')) { result[elem.substring(1, elem.length - 1)] = path[i] } else if (elem != path[i]) { return null } } return result } const router = { "/": (body, values) => RenderHomePage(body), "/images": (body, values) => RenderImageListPage(body, {headless: false}), "/images/{imageId}": (body, values) => RenderImagePage(body, values), "/boards": (body, values) => RenderBoardList(body), "/boards/{boardId}": (body, values) => RenderBoard(body, values), "/markdowns": (body, values) => RenderMarkdownList(body), "/markdowns/{markdownId}": (body, values) => RenderMarkdown(body, values), } const body = document.querySelector("#main-body") function Route(path) { RenderHeader() for (let route in router) { const match = matchRoute(route, path) if (match !== null) { router[route](body, match) console.log("routed", route) return } } console.log("none routed") } Route(window.location.pathname)