mingo
Version:
MongoDB query language for in-memory objects
85 lines (84 loc) • 2.65 kB
JavaScript
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var internal_exports = {};
__export(internal_exports, {
cached: () => cached,
rank: () => rank,
withMemo: () => withMemo
});
module.exports = __toCommonJS(internal_exports);
var import_util = require("../../util");
var import_push = require("../accumulator/push");
const memo = /* @__PURE__ */ new WeakMap();
const cached = (xs) => memo.has(xs);
function withMemo(collection, expr, initialize, fn) {
if (!memo.has(collection)) {
memo.set(collection, {});
}
const data = memo.get(collection);
if (!(expr.field in data)) {
data[expr.field] = initialize();
}
let ok = false;
try {
const res = fn(data[expr.field]);
ok = true;
return res;
} finally {
if (!ok) {
memo.delete(collection);
} else if (expr.documentNumber === collection.length) {
delete data[expr.field];
if (Object.keys(data).length === 0) memo.delete(collection);
}
}
}
function rank(_, collection, expr, options, dense) {
return withMemo(
collection,
expr,
() => {
const sortKey = "$" + Object.keys(expr.parentExpr.sortBy)[0];
const values = (0, import_push.$push)(collection, sortKey, options);
const groups = (0, import_util.groupBy)(
values,
((_2, n) => values[n])
);
let i = 0;
let offset = 0;
for (const key of groups.keys()) {
const len = groups.get(key).length;
groups.set(key, [i++, offset]);
offset += len;
}
return { values, groups };
},
({ values, groups }) => {
if (groups.size == collection.length) return expr.documentNumber;
const current = values[expr.documentNumber - 1];
const [i, n] = groups.get(current);
return (dense ? i : n) + 1;
}
);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
cached,
rank,
withMemo
});