Skip to content

Instantly share code, notes, and snippets.

@davidfowl
Forked from sajclarke/trie.js
Last active January 13, 2022 02:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidfowl/f31053b12d6bc3d354c2773dd7f9a892 to your computer and use it in GitHub Desktop.
Save davidfowl/f31053b12d6bc3d354c2773dd7f9a892 to your computer and use it in GitHub Desktop.
Building a trie using Javascript.
// Question: Implement a route matching enging
// Given a list of routes as a list of strings and a matching route, build a route matching engine
// that returns true if a path matches.
const routes = ['/foo/blah/bar', '/foo', '/products']
function buildTrie(routes) {
var root = { path: {} };
for (var route of routes) {
var node = root;
for (var segment of route.split('/')) {
if(segment.length === 0) continue;
if (node.path[segment] == null) {
node.path[segment] = { path: {} };
}
node = node.path[segment];
}
node.match = true;
}
return root;
}
function searchTrie(root, path) {
// Handle null/undefined paths
if (!path) return false;
var node = root;
for (var segment of path.split('/')) {
if (segment.length === 0) continue; // Skip empty segments?
node = node.path[segment];
if (!node) return false;
}
return node.match || false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment