Skip to content

Instantly share code, notes, and snippets.

@irskep

irskep/Router.ts Secret

Last active April 22, 2023 04:43
Show Gist options
  • Save irskep/704747b7a36fddd0cae7ffdf459427da to your computer and use it in GitHub Desktop.
Save irskep/704747b7a36fddd0cae7ffdf459427da to your computer and use it in GitHub Desktop.
export type RouteHandler = (...args: string[]) => void;
export type Route = {
re: RegExp | string;
handler: RouteHandler;
};
class Router {
routes: Route[];
constructor() {
this.routes = [];
window.addEventListener("popstate", (e) => this.check());
}
getFragment(): string {
return new URL(window.location.href).pathname;
}
add(re: RegExp | string, handler: RouteHandler) {
this.routes.push({ re, handler: handler });
}
remove(param: RouteHandler): void {
for (var i = 0, r; i < this.routes.length, (r = this.routes[i]); i++) {
if (r.handler === param || r.re.toString() === param.toString()) {
this.routes.splice(i, 1);
}
}
}
check(f?: string) {
const fragment = f || this.getFragment();
for (var i = 0; i < this.routes.length; i++) {
const match = fragment.match(this.routes[i].re);
if (match) {
match.shift();
this.routes[i].handler.apply({}, match);
return this;
}
}
console.error("No match for", fragment);
}
navigate(path: string) {
window.history.pushState({ path }, path, path);
this.check();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment