Tiny JS Router

javascript programming router

While working a personal project, I quickly created a 25 line client-side router for javascript.
It works really well with van.js.

// router.js
export default {
    routes: [],
    add(path, cb) { this.routes.push({ path, cb }) },
    listen(callback) {
        window.addEventListener('hashchange', () => {
            let url_parts = window.location.hash.substring(1).split("/").filter(e => e)
            this.routes.forEach(({ path, cb }) => {
                let path_parts = path.split("/").filter(e => e)
                let is_match = (url_parts.length == path_parts.length)
                        
                let params = {}
                path_parts.forEach((part, i) => {
                    let is_param = part.startsWith("{") && part.endsWith("}")
                    let is_the_same = part == url_parts[i]
                    
                    if (is_param) params[part.slice(1, -1)] = url_parts[i]
                    else is_match = is_the_same
                })

                if (is_match) callback(cb, params)
            })
        })
        window.dispatchEvent(new HashChangeEvent("hashchange"))
    },
}

// Example usage
import router from "./router.js"

router.add("/", () => "Home")

router.add("/profile/{name}", params => {
    return `<h1>Profile of ${params.name}</h1>`
})

router.listen((cb, params) => document.body.innerHTML = cb(params))