UNPKG

@thi.ng/router

Version:

Generic trie-based router with support for wildcards, route param validation/coercion, auth

37 lines (36 loc) 896 B
import { illegalArgs } from "@thi.ng/errors"; class Trie { n = {}; v; constructor(key, v, i = 0) { if (key && v !== void 0) { if (i < key.length) this.set(key, v, i); else this.v = v; } } set(key, v, i = 0) { if (i >= key.length) { this.v = v; return; } let k = key[i]; if (k === "+" && i < key.length - 1) illegalArgs("`+` only allowed in tail position"); if (k[0] === "?") k = "?"; const next = this.n[k]; if (next) next.set(key, v, i + 1); else this.n[k] = new Trie(key, v, i + 1); } get(key, i = 0) { if (i >= key.length) return this.v; let value; let next; if (next = this.n[key[i]]) value = next.get(key, i + 1); if (value !== void 0) return value; if (next = this.n["?"]) value = next.get(key, i + 1); return value !== void 0 ? value : this.n["+"]?.v; } } export { Trie };