42 lines
1.1 KiB
JavaScript
42 lines
1.1 KiB
JavaScript
import {
|
|
ComputeOptions,
|
|
computeValue
|
|
} from "../../core";
|
|
import { assert, groupBy, has } from "../../util";
|
|
const ID_KEY = "_id";
|
|
const $group = (collection, expr, options) => {
|
|
assert(has(expr, ID_KEY), "$group specification must include an '_id'");
|
|
const idExpr = expr[ID_KEY];
|
|
const copts = ComputeOptions.init(options);
|
|
const newFields = Object.keys(expr).filter((k) => k != ID_KEY);
|
|
return collection.transform((coll) => {
|
|
const partitions = groupBy(
|
|
coll,
|
|
(obj) => computeValue(obj, idExpr, null, options),
|
|
options.hashFunction
|
|
);
|
|
let i = -1;
|
|
const partitionKeys = Array.from(partitions.keys());
|
|
return () => {
|
|
if (++i === partitions.size) return { done: true };
|
|
const groupId = partitionKeys[i];
|
|
const obj = {};
|
|
if (groupId !== void 0) {
|
|
obj[ID_KEY] = groupId;
|
|
}
|
|
for (const key of newFields) {
|
|
obj[key] = computeValue(
|
|
partitions.get(groupId),
|
|
expr[key],
|
|
null,
|
|
copts.update(null, { groupId })
|
|
);
|
|
}
|
|
return { value: obj, done: false };
|
|
};
|
|
});
|
|
};
|
|
export {
|
|
$group
|
|
};
|