-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmemoizedNamespace.ts
105 lines (83 loc) · 2.75 KB
/
memoizedNamespace.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import { BlankNode, NamedNamespace, NamedNode, Namespace, TermIsh } from "rdflib";
import { NamespaceMap } from "../types";
import { defaultNS } from "./constants";
let termIndex = 0;
const termMap: Array<BlankNode | NamedNode> = [];
const nsMap: { [k: string]: NamedNode } = {};
const bnMap: { [k: string]: BlankNode } = {};
export function namedNodeByStoreIndex(un: number): NamedNode | undefined {
const term = termMap[un];
if (!term) {
return undefined;
}
if (term.termType === "NamedNode") {
return term;
}
return undefined;
}
export function nodeByStoreIndex(un: number): BlankNode | NamedNode | undefined {
return termMap[un];
}
export function blankNodeById(id: string): BlankNode {
const fromMap = bnMap[id];
if (fromMap !== undefined) {
return fromMap;
}
return addBn(new BlankNode(id));
}
export function namedNodeByIRI(iri: string): NamedNode {
const fromMap = nsMap[iri];
if (fromMap !== undefined) {
return fromMap;
}
const ln = iri.split(/[\/#]/).pop()!.split("?").shift() || "";
return add(new NamedNode(iri), ln);
}
function add(nn: NamedNode, ln: string): NamedNode {
nn.sI = ++termIndex;
nn.term = ln;
termMap[nn.sI] = nsMap[nn.value] = nn;
return nn;
}
function addBn(bn: BlankNode): BlankNode {
bn.sI = ++termIndex;
termMap[bn.sI] = bnMap[bn.value] = bn;
return bn;
}
export function memoizedNamespace(nsIRI: string): (ns: string) => NamedNode {
const ns = Namespace(nsIRI);
return (ln: string): NamedNode => {
const fullIRI = nsIRI + ln;
if (nsMap[fullIRI] !== undefined) {
return nsMap[fullIRI];
}
return add(ns(ln), ln);
};
}
const CI_MATCH_PREFIX = 0;
const CI_MATCH_SUFFIX = 1;
/**
* Expands a property if it's in short-form while preserving long-form.
* Note: The vocabulary needs to be present in the store prefix library
* @param prop The short- or long-form property
* @param namespaces Object of namespaces by their abbreviation.
* @returns The (expanded) property
*/
export function expandProperty(prop: NamedNode | TermIsh | string | undefined,
namespaces: NamespaceMap = defaultNS): NamedNode | undefined {
if (prop instanceof NamedNode || typeof prop === "undefined") {
return prop;
}
if (typeof prop === "object") {
if (prop.termType === "NamedNode") {
return namedNodeByIRI(prop.value);
}
return undefined;
}
if (prop.indexOf("/") >= 1) {
return namedNodeByIRI(prop);
}
const matches = prop.split(":");
const constructor: NamedNamespace | undefined = namespaces[matches[CI_MATCH_PREFIX]];
return constructor && constructor(matches[CI_MATCH_SUFFIX]);
}