-
-
Save davidfowl/f31053b12d6bc3d354c2773dd7f9a892 to your computer and use it in GitHub Desktop.
Building a trie using Javascript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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