From 7696a86fecda329292205bf1a28b6774afc91011 Mon Sep 17 00:00:00 2001 From: Chris Date: Wed, 18 Sep 2024 23:16:52 -0600 Subject: [PATCH] Adding $reduce operator (#28) * Adding $reduce operator * Tweak to argument order for $setField * Adding test for $rand and $rank --- index.ts | 9 ++++++++- pipeline.test.ts | 38 +++++++++++++++++++++++++++++++++++++- 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/index.ts b/index.ts index b174b5b..577ee75 100644 --- a/index.ts +++ b/index.ts @@ -2988,6 +2988,11 @@ const $rand = ne('$rand'); // TODO const $rank = ne('$rank'); +// TODO +const $reduce = (input: ObjectExpression, initialValue: Expression, inExpr: Expression) => ({ + $reduce: { input, initialValue, in: inExpr }, +}); + type RoundOperator = { $round: NumberExpression, }; @@ -3108,7 +3113,7 @@ const $setDifference = at('$setDifference'); const $setEquals = pta('$setEquals'); // TODO -const $setField = (field: string, value: Expression, input: ObjectExpression) => ({ +const $setField = (input: ObjectExpression, field: string, value: Expression) => ({ $setField: { field, input, value }, }); @@ -3956,6 +3961,8 @@ export = { rank: $rank, $redact, redact: $redact, + $reduce, + reduce: $reduce, $replaceRoot, replaceRoot: $replaceRoot, $replaceWith, diff --git a/pipeline.test.ts b/pipeline.test.ts index c481f63..f122ed1 100644 --- a/pipeline.test.ts +++ b/pipeline.test.ts @@ -1470,6 +1470,42 @@ describe('aggregation', () => { expect($.radiansToDegrees('$value')).toEqual({ $radiansToDegrees: '$value' }); }); }); + describe('$rand', () => { + it('exports expected vars', () => { + expect($.rand).toBeDefined(); + expect($.$rand).toBeDefined(); + expect($.rand).toStrictEqual($.$rand); + }); + it('returns expected result', () => { + expect($.rand()).toEqual({ $rand: {} }); + }); + }); + describe('$rank', () => { + it('exports expected vars', () => { + expect($.rank).toBeDefined(); + expect($.$rank).toBeDefined(); + expect($.rank).toStrictEqual($.$rank); + }); + it('returns expected result', () => { + expect($.rank()).toEqual({ $rank: {} }); + }); + }); + describe('$reduce', () => { + it('exports expected vars', () => { + expect($.reduce).toBeDefined(); + expect($.$reduce).toBeDefined(); + expect($.reduce).toStrictEqual($.$reduce); + }); + it('returns expected result', () => { + expect($.reduce('$input', 'foo', '$bar')).toEqual({ + $reduce: { + input: '$input', + initialValue: 'foo', + in: '$bar', + }, + }) + }); + }); describe('$round', () => { it('exports expected vars', () => { expect($.round).toBeDefined(); @@ -1555,7 +1591,7 @@ describe('aggregation', () => { expect($.setField).toStrictEqual($.$setField); }); it('returns expected result', () => { - expect($.setField('foo', '$value', '$doc')).toEqual({ + expect($.setField('$doc', 'foo', '$value')).toEqual({ $setField: { field: 'foo', value: '$value',