namespace-lookup
v0.3.0
Published
Find the longest namespace that a string starts with
Downloads
13
Readme
namespace-lookup
Find the longest prefix that a string starts with
This Node package implements a radix tree too efficiently look up whether a string starts with a prefix from a set of prefix strings.
Table of Contents
Install
npm install namespace-lookupUsage
import { Namespaces } from "namespace-lookup"
const namespaces = new Namespaces() // optionally pass an array of prefixes
namespaces.add("http://purl.org/dc/elements/1.1/")
namespaces.add("http://purl.org/dc/terms/")
namespaces.lookup("http://purl.org/dc/terms/title") // http://purl.org/dc/terms/
namespaces.lookup("http://schema.org/title") // undefinedAn alternative, less performant implementation is this (also exportable):
class NamespacesArray extends Set {
lookup(str) {
for (let namespace of [...this].sort((x,y) => y.length - x.length)) {
if (str.startsWith(namespace)) {
return namespace
}
}
}
}Class Namespaces also supports to add prefixes with a payload (any value except null) to be returned instead:
namespaces.add("http://purl.org/dc/elements/1.1/","dc")
namespaces.add("http://purl.org/dc/terms/","dct")
namespaces.lookup("http://purl.org/dc/terms/title") // dctPrefixes and payloads can also be passed as object:
namespaces = new Namespaces({
"http://purl.org/dc/elements/1.1/": "dc",
"http://purl.org/dc/terms/": "dct"
})Method tree returns a clean copy of the radix tree for debugging and vizualization.
const tree = namespaces.tree()
console.log(JSON.stringify(tree,0,2))Maintainers
- @nichtich (Jakob Voß)
Contribute
Contributions are welcome! Best use the issue tracker for questions, bug reports, and/or feature requests!
License
The implementation is based on a detailed description of the algorithm by Matt Roseman.
MIT license
