Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 10 additions & 22 deletions src/knowledge-collection-tools.js
Original file line number Diff line number Diff line change
Expand Up @@ -234,16 +234,16 @@ export function groupNquadsBySubject(nquadsArray, sort = false) {
const grouped = {};

parser.parse(nquadsArray.join("")).forEach((quad) => {
const { subject, predicate, object } = quad;
const { subject } = quad;

let subjectKey;
if (subject.termType === "Quad") {
const nestedSubject = subject.subject.value;
const nestedPredicate = subject.predicate.value;
const nestedObject =
subject.object.termType === "Literal"
? `"${escapeLiteral(subject.object.value)}"`
: `<${escapeLiteral(subject.object.value)}>`;
? `"${subject.object.value}"`
: `<${subject.object.value}>`;
subjectKey = `<<<${nestedSubject}> <${nestedPredicate}> ${nestedObject}>>`;
} else {
subjectKey = `<${subject.value}>`;
Expand All @@ -253,12 +253,14 @@ export function groupNquadsBySubject(nquadsArray, sort = false) {
grouped[subjectKey] = [];
}

const objectValue =
object.termType === "Literal"
? `"${escapeLiteral(object.value)}"`
: `<${escapeLiteral(object.value)}>`;
const writer = new N3.Writer({ format: "N-Quads" });
let quadString = "";
writer.addQuad(quad);
writer.end((error, result) => {
if (error) throw error;
quadString = result.trim();
});

const quadString = `${subjectKey} <${predicate.value}> ${objectValue} .`;
grouped[subjectKey].push(quadString);
});

Expand Down Expand Up @@ -401,17 +403,3 @@ ${nquadsArray.join('\n')}
function isEmptyObject(obj) {
return Object.keys(obj).length === 0 && obj.constructor === Object;
}

function escapeLiteral(value) {
const ESCAPE_MAP = {
'"': '\\"',
"\\": "\\\\",
"\b": "\\b",
"\f": "\\f",
"\n": "\\n",
"\r": "\\r",
"\t": "\\t",
};

return value.replace(/["\\\b\f\n\r\t]/g, (char) => ESCAPE_MAP[char]);
}
Loading