Debian Codegraph @

src/N3Store.js

raw
1 // **N3Store** objects store N3 quads by graph in memory.
2 import { default as N3DataFactory, termToId, termFromId } from './N3DataFactory';
3 import { Readable } from 'readable-stream';
4 import namespaces from './IRIs';
5
6 // ## Constructor
7 export default class N3Store {
8 constructor(quads, options) {
9 // The number of quads is initially zero
10 this._size = 0;
11 // `_graphs` contains subject, predicate, and object indexes per graph
12 this._graphs = Object.create(null);
13 // `_ids` maps entities such as `http://xmlns.com/foaf/0.1/name` to numbers,
14 // saving memory by using only numbers as keys in `_graphs`
15 this._id = 0;
16 this._ids = Object.create(null);
17 this._ids['><'] = 0; // dummy entry, so the first actual key is non-zero
18 this._entities = Object.create(null); // inverse of `_ids`
19 // `_blankNodeIndex` is the index of the last automatically named blank node
20 this._blankNodeIndex = 0;
21
22 // Shift parameters if `quads` is not given
23 if (!options && quads && !quads[0])
24 options = quads, quads = null;
25 options = options || {};
26 this._factory = options.factory || N3DataFactory;
27
28 // Add quads if passed
29 if (quads)
30 this.addQuads(quads);
31 }
32
33 // ## Public properties
34
35 // ### `size` returns the number of quads in the store
36 get size() {
37 // Return the quad count if if was cached
38 let size = this._size;
39 if (size !== null)
40 return size;
41
42 // Calculate the number of quads by counting to the deepest level
43 size = 0;
44 const graphs = this._graphs;
45 let subjects, subject;
46 for (const graphKey in graphs)
47 for (const subjectKey in (subjects = graphs[graphKey].subjects))
48 for (const predicateKey in (subject = subjects[subjectKey]))
49 size += Object.keys(subject[predicateKey]).length;
50 return this._size = size;
51 }
52
53 // ## Private methods
54
55 // ### `_addToIndex` adds a quad to a three-layered index.
56 // Returns if the index has changed, if the entry did not already exist.
57 _addToIndex(index0, key0, key1, key2) {
58 // Create layers as necessary
59 const index1 = index0[key0] || (index0[key0] = {});
60 const index2 = index1[key1] || (index1[key1] = {});
61 // Setting the key to _any_ value signals the presence of the quad
62 const existed = key2 in index2;
63 if (!existed)
64 index2[key2] = null;
65 return !existed;
66 }
67
68 // ### `_removeFromIndex` removes a quad from a three-layered index
69 _removeFromIndex(index0, key0, key1, key2) {
70 // Remove the quad from the index
71 const index1 = index0[key0], index2 = index1[key1];
72 delete index2[key2];
73
74 // Remove intermediary index layers if they are empty
75 for (const key in index2) return;
76 delete index1[key1];
77 for (const key in index1) return;
78 delete index0[key0];
79 }
80
81 // ### `_findInIndex` finds a set of quads in a three-layered index.
82 // The index base is `index0` and the keys at each level are `key0`, `key1`, and `key2`.
83 // Any of these keys can be undefined, which is interpreted as a wildcard.
84 // `name0`, `name1`, and `name2` are the names of the keys at each level,
85 // used when reconstructing the resulting quad
86 // (for instance: _subject_, _predicate_, and _object_).
87 // Finally, `graphId` will be the graph of the created quads.
88 *_findInIndex(index0, key0, key1, key2, name0, name1, name2, graphId) {
89 let tmp, index1, index2;
90 const entityKeys = this._entities;
91 const graph = termFromId(graphId, this._factory);
92 const parts = { subject: null, predicate: null, object: null };
93
94 // If a key is specified, use only that part of index 0.
95 if (key0) (tmp = index0, index0 = {})[key0] = tmp[key0];
96 for (const value0 in index0) {
97 if (index1 = index0[value0]) {
98 parts[name0] = termFromId(entityKeys[value0], this._factory);
99 // If a key is specified, use only that part of index 1.
100 if (key1) (tmp = index1, index1 = {})[key1] = tmp[key1];
101 for (const value1 in index1) {
102 if (index2 = index1[value1]) {
103 parts[name1] = termFromId(entityKeys[value1], this._factory);
104 // If a key is specified, use only that part of index 2, if it exists.
105 const values = key2 ? (key2 in index2 ? [key2] : []) : Object.keys(index2);
106 // Create quads for all items found in index 2.
107 for (let l = 0; l < values.length; l++) {
108 parts[name2] = termFromId(entityKeys[values[l]], this._factory);
109 yield this._factory.quad(parts.subject, parts.predicate, parts.object, graph);
110 }
111 }
112 }
113 }
114 }
115 }
116
117 // ### `_loop` executes the callback on all keys of index 0
118 _loop(index0, callback) {
119 for (const key0 in index0)
120 callback(key0);
121 }
122
123 // ### `_loopByKey0` executes the callback on all keys of a certain entry in index 0
124 _loopByKey0(index0, key0, callback) {
125 let index1, key1;
126 if (index1 = index0[key0]) {
127 for (key1 in index1)
128 callback(key1);
129 }
130 }
131
132 // ### `_loopByKey1` executes the callback on given keys of all entries in index 0
133 _loopByKey1(index0, key1, callback) {
134 let key0, index1;
135 for (key0 in index0) {
136 index1 = index0[key0];
137 if (index1[key1])
138 callback(key0);
139 }
140 }
141
142 // ### `_loopBy2Keys` executes the callback on given keys of certain entries in index 2
143 _loopBy2Keys(index0, key0, key1, callback) {
144 let index1, index2, key2;
145 if ((index1 = index0[key0]) && (index2 = index1[key1])) {
146 for (key2 in index2)
147 callback(key2);
148 }
149 }
150
151 // ### `_countInIndex` counts matching quads in a three-layered index.
152 // The index base is `index0` and the keys at each level are `key0`, `key1`, and `key2`.
153 // Any of these keys can be undefined, which is interpreted as a wildcard.
154 _countInIndex(index0, key0, key1, key2) {
155 let count = 0, tmp, index1, index2;
156
157 // If a key is specified, count only that part of index 0
158 if (key0) (tmp = index0, index0 = {})[key0] = tmp[key0];
159 for (const value0 in index0) {
160 if (index1 = index0[value0]) {
161 // If a key is specified, count only that part of index 1
162 if (key1) (tmp = index1, index1 = {})[key1] = tmp[key1];
163 for (const value1 in index1) {
164 if (index2 = index1[value1]) {
165 // If a key is specified, count the quad if it exists
166 if (key2) (key2 in index2) && count++;
167 // Otherwise, count all quads
168 else count += Object.keys(index2).length;
169 }
170 }
171 }
172 }
173 return count;
174 }
175
176 // ### `_getGraphs` returns an array with the given graph,
177 // or all graphs if the argument is null or undefined.
178 _getGraphs(graph) {
179 if (!isString(graph))
180 return this._graphs;
181 const graphs = {};
182 graphs[graph] = this._graphs[graph];
183 return graphs;
184 }
185
186 // ### `_uniqueEntities` returns a function that accepts an entity ID
187 // and passes the corresponding entity to callback if it hasn't occurred before.
188 _uniqueEntities(callback) {
189 const uniqueIds = Object.create(null);
190 return id => {
191 if (!(id in uniqueIds)) {
192 uniqueIds[id] = true;
193 callback(termFromId(this._entities[id], this._factory));
194 }
195 };
196 }
197
198 // ## Public methods
199
200 // ### `add` adds the specified quad to the dataset.
201 // Returns the dataset instance it was called on.
202 // Existing quads, as defined in Quad.equals, will be ignored.
203 add(quad) {
204 this.addQuad(quad);
205 return this;
206 }
207
208 // ### `addQuad` adds a new quad to the store.
209 // Returns if the quad index has changed, if the quad did not already exist.
210 addQuad(subject, predicate, object, graph) {
211 // Shift arguments if a quad object is given instead of components
212 if (!predicate)
213 graph = subject.graph, object = subject.object,
214 predicate = subject.predicate, subject = subject.subject;
215
216 // Convert terms to internal string representation
217 subject = termToId(subject);
218 predicate = termToId(predicate);
219 object = termToId(object);
220 graph = termToId(graph);
221
222 // Find the graph that will contain the triple
223 let graphItem = this._graphs[graph];
224 // Create the graph if it doesn't exist yet
225 if (!graphItem) {
226 graphItem = this._graphs[graph] = { subjects: {}, predicates: {}, objects: {} };
227 // Freezing a graph helps subsequent `add` performance,
228 // and properties will never be modified anyway
229 Object.freeze(graphItem);
230 }
231
232 // Since entities can often be long IRIs, we avoid storing them in every index.
233 // Instead, we have a separate index that maps entities to numbers,
234 // which are then used as keys in the other indexes.
235 const ids = this._ids;
236 const entities = this._entities;
237 subject = ids[subject] || (ids[entities[++this._id] = subject] = this._id);
238 predicate = ids[predicate] || (ids[entities[++this._id] = predicate] = this._id);
239 object = ids[object] || (ids[entities[++this._id] = object] = this._id);
240
241 const changed = this._addToIndex(graphItem.subjects, subject, predicate, object);
242 this._addToIndex(graphItem.predicates, predicate, object, subject);
243 this._addToIndex(graphItem.objects, object, subject, predicate);
244
245 // The cached quad count is now invalid
246 this._size = null;
247 return changed;
248 }
249
250 // ### `addQuads` adds multiple quads to the store
251 addQuads(quads) {
252 for (let i = 0; i < quads.length; i++)
253 this.addQuad(quads[i]);
254 }
255
256 // ### `delete` removes the specified quad from the dataset.
257 // Returns the dataset instance it was called on.
258 delete(quad) {
259 this.removeQuad(quad);
260 return this;
261 }
262
263 // ### `has` determines whether a dataset includes a certain quad or quad pattern.
264 has(subjectOrQuad, predicate, object, graph) {
265 if (subjectOrQuad && subjectOrQuad.subject)
266 ({ subject: subjectOrQuad, predicate, object, graph } = subjectOrQuad);
267 return !this.readQuads(subjectOrQuad, predicate, object, graph).next().done;
268 }
269
270 // ### `import` adds a stream of quads to the store
271 import(stream) {
272 stream.on('data', quad => { this.addQuad(quad); });
273 return stream;
274 }
275
276 // ### `removeQuad` removes a quad from the store if it exists
277 removeQuad(subject, predicate, object, graph) {
278 // Shift arguments if a quad object is given instead of components
279 if (!predicate)
280 graph = subject.graph, object = subject.object,
281 predicate = subject.predicate, subject = subject.subject;
282
283 // Convert terms to internal string representation
284 subject = termToId(subject);
285 predicate = termToId(predicate);
286 object = termToId(object);
287 graph = termToId(graph);
288
289 // Find internal identifiers for all components
290 // and verify the quad exists.
291 const ids = this._ids, graphs = this._graphs;
292 let graphItem, subjects, predicates;
293 if (!(subject = ids[subject]) || !(predicate = ids[predicate]) ||
294 !(object = ids[object]) || !(graphItem = graphs[graph]) ||
295 !(subjects = graphItem.subjects[subject]) ||
296 !(predicates = subjects[predicate]) ||
297 !(object in predicates))
298 return false;
299
300 // Remove it from all indexes
301 this._removeFromIndex(graphItem.subjects, subject, predicate, object);
302 this._removeFromIndex(graphItem.predicates, predicate, object, subject);
303 this._removeFromIndex(graphItem.objects, object, subject, predicate);
304 if (this._size !== null) this._size--;
305
306 // Remove the graph if it is empty
307 for (subject in graphItem.subjects) return true;
308 delete graphs[graph];
309 return true;
310 }
311
312 // ### `removeQuads` removes multiple quads from the store
313 removeQuads(quads) {
314 for (let i = 0; i < quads.length; i++)
315 this.removeQuad(quads[i]);
316 }
317
318 // ### `remove` removes a stream of quads from the store
319 remove(stream) {
320 stream.on('data', quad => { this.removeQuad(quad); });
321 return stream;
322 }
323
324 // ### `removeMatches` removes all matching quads from the store
325 // Setting any field to `undefined` or `null` indicates a wildcard.
326 removeMatches(subject, predicate, object, graph) {
327 const stream = new Readable({ objectMode: true });
328
329 stream._read = () => {
330 for (const quad of this.readQuads(subject, predicate, object, graph))
331 stream.push(quad);
332 stream.push(null);
333 };
334
335 return this.remove(stream);
336 }
337
338 // ### `deleteGraph` removes all triples with the given graph from the store
339 deleteGraph(graph) {
340 return this.removeMatches(null, null, null, graph);
341 }
342
343 // ### `getQuads` returns an array of quads matching a pattern.
344 // Setting any field to `undefined` or `null` indicates a wildcard.
345 getQuads(subject, predicate, object, graph) {
346 return [...this.readQuads(subject, predicate, object, graph)];
347 }
348
349 // ### `readQuads` returns an generator of quads matching a pattern.
350 // Setting any field to `undefined` or `null` indicates a wildcard.
351 *readQuads(subject, predicate, object, graph) {
352 // Convert terms to internal string representation
353 subject = subject && termToId(subject);
354 predicate = predicate && termToId(predicate);
355 object = object && termToId(object);
356 graph = graph && termToId(graph);
357
358 const graphs = this._getGraphs(graph), ids = this._ids;
359 let content, subjectId, predicateId, objectId;
360
361 // Translate IRIs to internal index keys.
362 if (isString(subject) && !(subjectId = ids[subject]) ||
363 isString(predicate) && !(predicateId = ids[predicate]) ||
364 isString(object) && !(objectId = ids[object]))
365 return;
366
367 for (const graphId in graphs) {
368 // Only if the specified graph contains triples, there can be results
369 if (content = graphs[graphId]) {
370 // Choose the optimal index, based on what fields are present
371 if (subjectId) {
372 if (objectId)
373 // If subject and object are given, the object index will be the fastest
374 yield* this._findInIndex(content.objects, objectId, subjectId, predicateId,
375 'object', 'subject', 'predicate', graphId);
376 else
377 // If only subject and possibly predicate are given, the subject index will be the fastest
378 yield* this._findInIndex(content.subjects, subjectId, predicateId, null,
379 'subject', 'predicate', 'object', graphId);
380 }
381 else if (predicateId)
382 // If only predicate and possibly object are given, the predicate index will be the fastest
383 yield* this._findInIndex(content.predicates, predicateId, objectId, null,
384 'predicate', 'object', 'subject', graphId);
385 else if (objectId)
386 // If only object is given, the object index will be the fastest
387 yield* this._findInIndex(content.objects, objectId, null, null,
388 'object', 'subject', 'predicate', graphId);
389 else
390 // If nothing is given, iterate subjects and predicates first
391 yield* this._findInIndex(content.subjects, null, null, null,
392 'subject', 'predicate', 'object', graphId);
393 }
394 }
395 }
396
397 // ### `match` returns a new dataset that is comprised of all quads in the current instance matching the given arguments.
398 // The logic described in Quad Matching is applied for each quad in this dataset to check if it should be included in the output dataset.
399 // Note: This method always returns a new DatasetCore, even if that dataset contains no quads.
400 // Note: Since a DatasetCore is an unordered set, the order of the quads within the returned sequence is arbitrary.
401 // Setting any field to `undefined` or `null` indicates a wildcard.
402 // For backwards compatibility, the object return also implements the Readable stream interface.
403 match(subject, predicate, object, graph) {
404 return new DatasetCoreAndReadableStream(this, subject, predicate, object, graph);
405 }
406
407 // ### `countQuads` returns the number of quads matching a pattern.
408 // Setting any field to `undefined` or `null` indicates a wildcard.
409 countQuads(subject, predicate, object, graph) {
410 // Convert terms to internal string representation
411 subject = subject && termToId(subject);
412 predicate = predicate && termToId(predicate);
413 object = object && termToId(object);
414 graph = graph && termToId(graph);
415
416 const graphs = this._getGraphs(graph), ids = this._ids;
417 let count = 0, content, subjectId, predicateId, objectId;
418
419 // Translate IRIs to internal index keys.
420 if (isString(subject) && !(subjectId = ids[subject]) ||
421 isString(predicate) && !(predicateId = ids[predicate]) ||
422 isString(object) && !(objectId = ids[object]))
423 return 0;
424
425 for (const graphId in graphs) {
426 // Only if the specified graph contains triples, there can be results
427 if (content = graphs[graphId]) {
428 // Choose the optimal index, based on what fields are present
429 if (subject) {
430 if (object)
431 // If subject and object are given, the object index will be the fastest
432 count += this._countInIndex(content.objects, objectId, subjectId, predicateId);
433 else
434 // If only subject and possibly predicate are given, the subject index will be the fastest
435 count += this._countInIndex(content.subjects, subjectId, predicateId, objectId);
436 }
437 else if (predicate) {
438 // If only predicate and possibly object are given, the predicate index will be the fastest
439 count += this._countInIndex(content.predicates, predicateId, objectId, subjectId);
440 }
441 else {
442 // If only object is possibly given, the object index will be the fastest
443 count += this._countInIndex(content.objects, objectId, subjectId, predicateId);
444 }
445 }
446 }
447 return count;
448 }
449
450 // ### `forEach` executes the callback on all quads.
451 // Setting any field to `undefined` or `null` indicates a wildcard.
452 forEach(callback, subject, predicate, object, graph) {
453 this.some(quad => {
454 callback(quad);
455 return false;
456 }, subject, predicate, object, graph);
457 }
458
459 // ### `every` executes the callback on all quads,
460 // and returns `true` if it returns truthy for all them.
461 // Setting any field to `undefined` or `null` indicates a wildcard.
462 every(callback, subject, predicate, object, graph) {
463 let some = false;
464 const every = !this.some(quad => {
465 some = true;
466 return !callback(quad);
467 }, subject, predicate, object, graph);
468 return some && every;
469 }
470
471 // ### `some` executes the callback on all quads,
472 // and returns `true` if it returns truthy for any of them.
473 // Setting any field to `undefined` or `null` indicates a wildcard.
474 some(callback, subject, predicate, object, graph) {
475 for (const quad of this.readQuads(subject, predicate, object, graph))
476 if (callback(quad))
477 return true;
478 return false;
479 }
480
481 // ### `getSubjects` returns all subjects that match the pattern.
482 // Setting any field to `undefined` or `null` indicates a wildcard.
483 getSubjects(predicate, object, graph) {
484 const results = [];
485 this.forSubjects(s => { results.push(s); }, predicate, object, graph);
486 return results;
487 }
488
489 // ### `forSubjects` executes the callback on all subjects that match the pattern.
490 // Setting any field to `undefined` or `null` indicates a wildcard.
491 forSubjects(callback, predicate, object, graph) {
492 // Convert terms to internal string representation
493 predicate = predicate && termToId(predicate);
494 object = object && termToId(object);
495 graph = graph && termToId(graph);
496
497 const ids = this._ids, graphs = this._getGraphs(graph);
498 let content, predicateId, objectId;
499 callback = this._uniqueEntities(callback);
500
501 // Translate IRIs to internal index keys.
502 if (isString(predicate) && !(predicateId = ids[predicate]) ||
503 isString(object) && !(objectId = ids[object]))
504 return;
505
506 for (graph in graphs) {
507 // Only if the specified graph contains triples, there can be results
508 if (content = graphs[graph]) {
509 // Choose optimal index based on which fields are wildcards
510 if (predicateId) {
511 if (objectId)
512 // If predicate and object are given, the POS index is best.
513 this._loopBy2Keys(content.predicates, predicateId, objectId, callback);
514 else
515 // If only predicate is given, the SPO index is best.
516 this._loopByKey1(content.subjects, predicateId, callback);
517 }
518 else if (objectId)
519 // If only object is given, the OSP index is best.
520 this._loopByKey0(content.objects, objectId, callback);
521 else
522 // If no params given, iterate all the subjects
523 this._loop(content.subjects, callback);
524 }
525 }
526 }
527
528 // ### `getPredicates` returns all predicates that match the pattern.
529 // Setting any field to `undefined` or `null` indicates a wildcard.
530 getPredicates(subject, object, graph) {
531 const results = [];
532 this.forPredicates(p => { results.push(p); }, subject, object, graph);
533 return results;
534 }
535
536 // ### `forPredicates` executes the callback on all predicates that match the pattern.
537 // Setting any field to `undefined` or `null` indicates a wildcard.
538 forPredicates(callback, subject, object, graph) {
539 // Convert terms to internal string representation
540 subject = subject && termToId(subject);
541 object = object && termToId(object);
542 graph = graph && termToId(graph);
543
544 const ids = this._ids, graphs = this._getGraphs(graph);
545 let content, subjectId, objectId;
546 callback = this._uniqueEntities(callback);
547
548 // Translate IRIs to internal index keys.
549 if (isString(subject) && !(subjectId = ids[subject]) ||
550 isString(object) && !(objectId = ids[object]))
551 return;
552
553 for (graph in graphs) {
554 // Only if the specified graph contains triples, there can be results
555 if (content = graphs[graph]) {
556 // Choose optimal index based on which fields are wildcards
557 if (subjectId) {
558 if (objectId)
559 // If subject and object are given, the OSP index is best.
560 this._loopBy2Keys(content.objects, objectId, subjectId, callback);
561 else
562 // If only subject is given, the SPO index is best.
563 this._loopByKey0(content.subjects, subjectId, callback);
564 }
565 else if (objectId)
566 // If only object is given, the POS index is best.
567 this._loopByKey1(content.predicates, objectId, callback);
568 else
569 // If no params given, iterate all the predicates.
570 this._loop(content.predicates, callback);
571 }
572 }
573 }
574
575 // ### `getObjects` returns all objects that match the pattern.
576 // Setting any field to `undefined` or `null` indicates a wildcard.
577 getObjects(subject, predicate, graph) {
578 const results = [];
579 this.forObjects(o => { results.push(o); }, subject, predicate, graph);
580 return results;
581 }
582
583 // ### `forObjects` executes the callback on all objects that match the pattern.
584 // Setting any field to `undefined` or `null` indicates a wildcard.
585 forObjects(callback, subject, predicate, graph) {
586 // Convert terms to internal string representation
587 subject = subject && termToId(subject);
588 predicate = predicate && termToId(predicate);
589 graph = graph && termToId(graph);
590
591 const ids = this._ids, graphs = this._getGraphs(graph);
592 let content, subjectId, predicateId;
593 callback = this._uniqueEntities(callback);
594
595 // Translate IRIs to internal index keys.
596 if (isString(subject) && !(subjectId = ids[subject]) ||
597 isString(predicate) && !(predicateId = ids[predicate]))
598 return;
599
600 for (graph in graphs) {
601 // Only if the specified graph contains triples, there can be results
602 if (content = graphs[graph]) {
603 // Choose optimal index based on which fields are wildcards
604 if (subjectId) {
605 if (predicateId)
606 // If subject and predicate are given, the SPO index is best.
607 this._loopBy2Keys(content.subjects, subjectId, predicateId, callback);
608 else
609 // If only subject is given, the OSP index is best.
610 this._loopByKey1(content.objects, subjectId, callback);
611 }
612 else if (predicateId)
613 // If only predicate is given, the POS index is best.
614 this._loopByKey0(content.predicates, predicateId, callback);
615 else
616 // If no params given, iterate all the objects.
617 this._loop(content.objects, callback);
618 }
619 }
620 }
621
622 // ### `getGraphs` returns all graphs that match the pattern.
623 // Setting any field to `undefined` or `null` indicates a wildcard.
624 getGraphs(subject, predicate, object) {
625 const results = [];
626 this.forGraphs(g => { results.push(g); }, subject, predicate, object);
627 return results;
628 }
629
630 // ### `forGraphs` executes the callback on all graphs that match the pattern.
631 // Setting any field to `undefined` or `null` indicates a wildcard.
632 forGraphs(callback, subject, predicate, object) {
633 for (const graph in this._graphs) {
634 this.some(quad => {
635 callback(quad.graph);
636 return true; // Halt iteration of some()
637 }, subject, predicate, object, graph);
638 }
639 }
640
641 // ### `createBlankNode` creates a new blank node, returning its name
642 createBlankNode(suggestedName) {
643 let name, index;
644 // Generate a name based on the suggested name
645 if (suggestedName) {
646 name = suggestedName = `_:${suggestedName}`, index = 1;
647 while (this._ids[name])
648 name = suggestedName + index++;
649 }
650 // Generate a generic blank node name
651 else {
652 do { name = `_:b${this._blankNodeIndex++}`; }
653 while (this._ids[name]);
654 }
655 // Add the blank node to the entities, avoiding the generation of duplicates
656 this._ids[name] = ++this._id;
657 this._entities[this._id] = name;
658 return this._factory.blankNode(name.substr(2));
659 }
660
661 // ### `extractLists` finds and removes all list triples
662 // and returns the items per list.
663 extractLists({ remove = false, ignoreErrors = false } = {}) {
664 const lists = {}; // has scalar keys so could be a simple Object
665 const onError = ignoreErrors ? (() => true) :
666 ((node, message) => { throw new Error(`${node.value} ${message}`); });
667
668 // Traverse each list from its tail
669 const tails = this.getQuads(null, namespaces.rdf.rest, namespaces.rdf.nil, null);
670 const toRemove = remove ? [...tails] : [];
671 tails.forEach(tailQuad => {
672 const items = []; // the members found as objects of rdf:first quads
673 let malformed = false; // signals whether the current list is malformed
674 let head; // the head of the list (_:b1 in above example)
675 let headPos; // set to subject or object when head is set
676 const graph = tailQuad.graph; // make sure list is in exactly one graph
677
678 // Traverse the list from tail to end
679 let current = tailQuad.subject;
680 while (current && !malformed) {
681 const objectQuads = this.getQuads(null, null, current, null);
682 const subjectQuads = this.getQuads(current, null, null, null);
683 let quad, first = null, rest = null, parent = null;
684
685 // Find the first and rest of this list node
686 for (let i = 0; i < subjectQuads.length && !malformed; i++) {
687 quad = subjectQuads[i];
688 if (!quad.graph.equals(graph))
689 malformed = onError(current, 'not confined to single graph');
690 else if (head)
691 malformed = onError(current, 'has non-list arcs out');
692
693 // one rdf:first
694 else if (quad.predicate.value === namespaces.rdf.first) {
695 if (first)
696 malformed = onError(current, 'has multiple rdf:first arcs');
697 else
698 toRemove.push(first = quad);
699 }
700
701 // one rdf:rest
702 else if (quad.predicate.value === namespaces.rdf.rest) {
703 if (rest)
704 malformed = onError(current, 'has multiple rdf:rest arcs');
705 else
706 toRemove.push(rest = quad);
707 }
708
709 // alien triple
710 else if (objectQuads.length)
711 malformed = onError(current, 'can\'t be subject and object');
712 else {
713 head = quad; // e.g. { (1 2 3) :p :o }
714 headPos = 'subject';
715 }
716 }
717
718 // { :s :p (1 2) } arrives here with no head
719 // { (1 2) :p :o } arrives here with head set to the list.
720 for (let i = 0; i < objectQuads.length && !malformed; ++i) {
721 quad = objectQuads[i];
722 if (head)
723 malformed = onError(current, 'can\'t have coreferences');
724 // one rdf:rest
725 else if (quad.predicate.value === namespaces.rdf.rest) {
726 if (parent)
727 malformed = onError(current, 'has incoming rdf:rest arcs');
728 else
729 parent = quad;
730 }
731 else {
732 head = quad; // e.g. { :s :p (1 2) }
733 headPos = 'object';
734 }
735 }
736
737 // Store the list item and continue with parent
738 if (!first)
739 malformed = onError(current, 'has no list head');
740 else
741 items.unshift(first.object);
742 current = parent && parent.subject;
743 }
744
745 // Don't remove any quads if the list is malformed
746 if (malformed)
747 remove = false;
748 // Store the list under the value of its head
749 else if (head)
750 lists[head[headPos].value] = items;
751 });
752
753 // Remove list quads if requested
754 if (remove)
755 this.removeQuads(toRemove);
756 return lists;
757 }
758
759 // ### Store is an iterable.
760 // Can be used where iterables are expected: for...of loops, array spread operator,
761 // `yield*`, and destructuring assignment (order is not guaranteed).
762 *[Symbol.iterator]() {
763 yield* this.readQuads();
764 }
765 }
766
767 // Determines whether the argument is a string
768 function isString(s) {
769 return typeof s === 'string' || s instanceof String;
770 }
771
772 /**
773 * A class that implements both DatasetCore and Readable.
774 */
775 class DatasetCoreAndReadableStream extends Readable {
776 constructor(n3Store, subject, predicate, object, graph) {
777 super({ objectMode: true });
778 Object.assign(this, { n3Store, subject, predicate, object, graph });
779 }
780
781 get filtered() {
782 if (!this._filtered) {
783 const { n3Store, graph, object, predicate, subject } = this;
784 const newStore = this._filtered = new N3Store({ factory: n3Store._factory });
785 for (const quad of n3Store.readQuads(subject, predicate, object, graph))
786 newStore.addQuad(quad);
787 }
788 return this._filtered;
789 }
790
791 get size() {
792 return this.filtered.size;
793 }
794
795 _read() {
796 for (const quad of this)
797 this.push(quad);
798 this.push(null);
799 }
800
801 add(quad) {
802 return this.filtered.add(quad);
803 }
804
805 delete(quad) {
806 return this.filtered.delete(quad);
807 }
808
809 has(quad) {
810 return this.filtered.has(quad);
811 }
812
813 match(subject, predicate, object, graph) {
814 return new DatasetCoreAndReadableStream(this.filtered, subject, predicate, object, graph);
815 }
816
817 *[Symbol.iterator]() {
818 yield* this._filtered || this.n3Store.readQuads(this.subject, this.predicate, this.object, this.graph);
819 }
820 }