vector-im-hydrogen-web/src/matrix/storage/idb/query-target.js

97 lines
2.2 KiB
JavaScript
Raw Normal View History

2019-02-07 01:20:27 +01:00
import {iterateCursor} from "./utils.js";
2019-02-05 00:21:50 +01:00
export default class QueryTarget {
2019-02-07 01:20:27 +01:00
constructor(target) {
this._target = target;
}
reduce(range, reducer, initialValue) {
return this._reduce(range, reducer, initialValue, "next");
}
reduceReverse(range, reducer, initialValue) {
return this._reduce(range, reducer, initialValue, "next");
}
selectLimit(range, amount) {
return this._selectLimit(range, amount, "next");
}
selectLimitReverse(range, amount) {
return this._selectLimit(range, amount, "prev");
}
selectWhile(range, predicate) {
return this._selectWhile(range, predicate, "next");
}
selectWhileReverse(range, predicate) {
return this._selectWhile(range, predicate, "prev");
}
2019-02-10 21:25:29 +01:00
async selectAll(range, direction) {
2019-02-07 01:20:27 +01:00
const cursor = this._target.openCursor(range, direction);
const results = [];
2019-02-10 21:25:29 +01:00
await iterateCursor(cursor, (value) => {
results.push(value);
return true;
});
2019-02-10 21:25:29 +01:00
return results;
}
selectFirst(range) {
return this._find(range, () => true, "next");
}
selectLast(range) {
return this._find(range, () => true, "prev");
}
find(range, predicate) {
return this._find(range, predicate, "next");
}
findReverse(range, predicate) {
return this._find(range, predicate, "prev");
}
_reduce(range, reducer, initialValue, direction) {
let reducedValue = initialValue;
2019-02-07 01:20:27 +01:00
const cursor = this._target.openCursor(range, direction);
return iterateCursor(cursor, (value) => {
reducedValue = reducer(reducedValue, value);
return true;
});
}
_selectLimit(range, amount, direction) {
return this._selectWhile(range, (results) => {
return results.length === amount;
}, direction);
}
2019-02-10 21:25:29 +01:00
async _selectWhile(range, predicate, direction) {
2019-02-07 01:20:27 +01:00
const cursor = this._target.openCursor(range, direction);
const results = [];
2019-02-10 21:25:29 +01:00
await iterateCursor(cursor, (value) => {
results.push(value);
return predicate(results);
});
2019-02-10 21:25:29 +01:00
return results;
}
async _find(range, predicate, direction) {
2019-02-07 01:20:27 +01:00
const cursor = this._target.openCursor(range, direction);
let result;
const found = await iterateCursor(cursor, (value) => {
2019-02-07 01:20:27 +01:00
const found = predicate(value);
if (found) {
result = value;
}
2019-02-07 01:20:27 +01:00
return found;
});
2019-02-07 01:20:27 +01:00
if (found) {
return result;
}
}
}