@jahed/sparql-engine
Version:
SPARQL query engine for servers and web browsers.
52 lines • 1.81 kB
JavaScript
import { Pipeline } from "../engine/pipeline/pipeline.js";
import { Bindings } from "../rdf/bindings.js";
import { termToValue, UNBOUND } from "../utils/rdf.js";
/**
* Build a comparator function from an ORDER BY clause content
* @private
* @param comparators - ORDER BY comparators
* @return A comparator function
*/
function _compileComparators(comparators) {
const comparatorsFuncs = comparators.map((c) => {
return (left, right) => {
const expr = c.expression.value;
const a = termToValue(left.get(expr) || UNBOUND);
const b = termToValue(right.get(expr) || UNBOUND);
if (a < b) {
return c.descending ? 1 : -1;
}
else if (a > b) {
return c.descending ? -1 : 1;
}
return 0;
};
});
return (left, right) => {
let temp;
for (let comp of comparatorsFuncs) {
temp = comp(left, right);
if (temp !== 0) {
return temp;
}
}
return 0;
};
}
/**
* A OrderByOperator implements a ORDER BY clause, i.e.,
* it sorts solution mappings produced by another operator
* @see {@link https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#modOrderBy}
* @param source - Input {@link PipelineStage}
* @param comparators - Set of ORDER BY comparators
* @return A {@link PipelineStage} which evaluate the ORDER BY operation
*/
export default function orderby(source, comparators) {
const comparator = _compileComparators(comparators);
const engine = Pipeline.getInstance();
return engine.mergeMap(engine.collect(source), (values) => {
values.sort((a, b) => comparator(a, b));
return engine.from(values);
});
}
//# sourceMappingURL=orderby.js.map