/
firstN.ts
38 lines (36 loc) · 1.12 KB
/
firstN.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// https://www.mongodb.com/docs/manual/reference/operator/aggregation/firstN/
import {
AccumulatorOperator,
ComputeOptions,
computeValue,
Options
} from "../../core";
import { AnyVal, RawObject } from "../../types";
import { $push } from "./push";
interface InputExpr {
n: AnyVal;
input: AnyVal;
}
/**
* Returns an aggregation of the first n elements within a group. The elements returned are meaningful only if in a specified sort order.
* If the group contains fewer than n elements, $firstN returns all elements in the group.
*
* @param {Array} collection The input array
* @param {Object} expr The right-hand side expression value of the operator
* @param {Options} options The options to use for this operation
* @returns {*}
*/
export const $firstN: AccumulatorOperator = (
collection: RawObject[],
expr: InputExpr,
options: Options
): AnyVal[] => {
const copts = ComputeOptions.init(options);
const m = collection.length;
const n = computeValue(copts?.local?.groupId, expr.n, null, copts) as number;
return $push(
m <= n ? collection : collection.slice(0, n),
expr.input,
options
);
};