@tpluscode/rdfine
Version:
RDF/JS idiomatic, native, effective
78 lines (77 loc) • 2.85 kB
JavaScript
import { onlyUnique } from './filter.js';
import * as compare from './compare.js';
function getNode(value, RDF) {
if (typeof value === 'string') {
return RDF.namedNode(value);
}
if ('termType' in value) {
return value;
}
return value.id;
}
export default class {
add(value) {
this.__resource.pointer.addOut(this.__resource.env.ns.rdf.type, getNode(value, this.__resource.env));
return this;
}
clear() {
this.__graph.deleteOut(this.__resource.env.ns.rdf.type);
}
delete(value) {
const deletedQuads = this.__graph.dataset.match(this.__resource.id, this.__resource.env.ns.rdf.type, getNode(value, this.__resource.env));
for (const quad of deletedQuads) {
this.__graph.dataset.delete(quad);
}
return deletedQuads.size > 0;
}
forEach(callbackfn, thisArg) {
for (const value of this.values()) {
callbackfn.call(thisArg, value, value, this);
}
}
has(value) {
return this.__graph.has(this.__resource.env.ns.rdf.type, getNode(value, this.__resource.env)).terms.length > 0;
}
get size() {
return this.__graph.out(this.__resource.env.ns.rdf.type).terms.filter(onlyUnique(compare.terms)).length;
}
[Symbol.iterator]() {
return this.values();
}
entries() {
return this.__values.map(res => [res, res])[Symbol.iterator]();
}
keys() {
return this.values();
}
values() {
return this.__values[Symbol.iterator]();
}
get [Symbol.toStringTag]() {
return this.__values.toString();
}
constructor(resource, allGraphs = false) {
this.__resource = resource;
this.__allGraphs = allGraphs;
// TODO: when clownface gets graph feature
// this.__graph = allGraphs ? resource.pointer.fromUnionGraph() : resource.pointer
this.__graph = allGraphs ? resource.env.clownface({ dataset: resource.pointer.dataset, term: resource.pointer.term, graph: undefined }) : resource.pointer;
}
get __values() {
const graphId = !this.__allGraphs ? this.__resource._graphId : null;
// TODO: when clownface gets graph feature
// const types: MultiPointer<Term, D> = this.__resource.pointer.from(graphId).out(rdf.type)
const typeQuads = this.__graph.dataset.match(this.__resource.id, this.__resource.env.ns.rdf.type, null, graphId);
const types = [...typeQuads]
.map(quad => {
return this.__resource.env.clownface({
dataset: this.__graph.dataset,
term: quad.object,
graph: quad.graph,
});
});
return types
.map(type => this.__resource._create(type))
.filter(onlyUnique(compare.resources(false)));
}
}