Debian Codegraph @

src/N3Util.js

raw
1 // **N3Util** provides N3 utility functions.
2
3 import N3DataFactory from './N3DataFactory';
4
5 // Tests whether the given term represents an IRI
6 export function isNamedNode(term) {
7 return !!term && term.termType === 'NamedNode';
8 }
9
10 // Tests whether the given term represents a blank node
11 export function isBlankNode(term) {
12 return !!term && term.termType === 'BlankNode';
13 }
14
15 // Tests whether the given term represents a literal
16 export function isLiteral(term) {
17 return !!term && term.termType === 'Literal';
18 }
19
20 // Tests whether the given term represents a variable
21 export function isVariable(term) {
22 return !!term && term.termType === 'Variable';
23 }
24
25 // Tests whether the given term represents the default graph
26 export function isDefaultGraph(term) {
27 return !!term && term.termType === 'DefaultGraph';
28 }
29
30 // Tests whether the given quad is in the default graph
31 export function inDefaultGraph(quad) {
32 return isDefaultGraph(quad.graph);
33 }
34
35 // Creates a function that prepends the given IRI to a local name
36 export function prefix(iri, factory) {
37 return prefixes({ '': iri.value || iri }, factory)('');
38 }
39
40 // Creates a function that allows registering and expanding prefixes
41 export function prefixes(defaultPrefixes, factory) {
42 // Add all of the default prefixes
43 const prefixes = Object.create(null);
44 for (const prefix in defaultPrefixes)
45 processPrefix(prefix, defaultPrefixes[prefix]);
46 // Set the default factory if none was specified
47 factory = factory || N3DataFactory;
48
49 // Registers a new prefix (if an IRI was specified)
50 // or retrieves a function that expands an existing prefix (if no IRI was specified)
51 function processPrefix(prefix, iri) {
52 // Create a new prefix if an IRI is specified or the prefix doesn't exist
53 if (typeof iri === 'string') {
54 // Create a function that expands the prefix
55 const cache = Object.create(null);
56 prefixes[prefix] = local => {
57 return cache[local] || (cache[local] = factory.namedNode(iri + local));
58 };
59 }
60 else if (!(prefix in prefixes)) {
61 throw new Error(`Unknown prefix: ${prefix}`);
62 }
63 return prefixes[prefix];
64 }
65 return processPrefix;
66 }