Skip to content

Commit 212cbfb

Browse files
committed
feat: sum function
1 parent 05a2f66 commit 212cbfb

File tree

2 files changed

+18
-4
lines changed

2 files changed

+18
-4
lines changed

packages/jmespath/src/functions/Functions.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,19 @@ class Functions {
235235
return str.startsWith(suffix);
236236
}
237237

238+
/**
239+
* Sum the provided numbers.
240+
*
241+
* @param args The numbers to sum
242+
* @returns The sum of the numbers
243+
*/
244+
@Functions.signature({
245+
argumentsSpecs: [['array-number']],
246+
})
247+
public funcSum(args: Array<number>): number {
248+
return args.reduce((a, b) => a + b, 0);
249+
}
250+
238251
/**
239252
* Convert the provided value to an array.
240253
*

packages/jmespath/tests/unit/functions.test.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1240,7 +1240,7 @@ describe('Functions tests', () => {
12401240
expect(() => search(expression, data)).toThrow(error);
12411241
});
12421242

1243-
/* it.each([
1243+
it.each([
12441244
{
12451245
expression: 'sum(numbers)',
12461246
expected: 11,
@@ -1288,18 +1288,17 @@ describe('Functions tests', () => {
12881288
{
12891289
expression: 'sum(array)',
12901290
error:
1291-
'TypeError: sum() expected argument 1 to be type (Array<number>) but received type array instead.',
1291+
'Invalid argument type for function sum(), expected "array-number" but found "null" in expression: sum(array)',
12921292
},
12931293
])('sum() function errors', ({ expression, error }) => {
1294-
// TODO: see if we can assert the error type as well in sum() errors tests
12951294
// Prepare
12961295
const data = {
12971296
type: 'object',
12981297
};
12991298

13001299
// Act & Assess
13011300
expect(() => search(expression, data)).toThrow(error);
1302-
}); */
1301+
});
13031302

13041303
it.each([
13051304
{
@@ -1539,6 +1538,7 @@ describe('Functions tests', () => {
15391538
// Act & Assess
15401539
expect(() => search(expression, data)).toThrow(error);
15411540
}); */
1541+
15421542
/* it.each([
15431543
{
15441544
description: 'function projection on variadic function',
@@ -1581,6 +1581,7 @@ describe('Functions tests', () => {
15811581
expect(result).toStrictEqual(expected);
15821582
}
15831583
); */
1584+
15841585
/* it.each([
15851586
{
15861587
description: 'sort by field expression',

0 commit comments

Comments
 (0)