Skip to content

Commit 0b5ae30

Browse files
authored
Implement add/1 (#3144)
1 parent 137018d commit 0b5ae30

File tree

5 files changed

+35
-4
lines changed

5 files changed

+35
-4
lines changed

docs/content/manual/dev/manual.yml

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1300,7 +1300,7 @@ sections:
13001300
input: '[1,[[],{"a":2}]]'
13011301
output: ['[[0],[1,1,"a"]]']
13021302

1303-
- title: "`add`"
1303+
- title: "`add`, `add(generator)`"
13041304
body: |
13051305
13061306
The filter `add` takes as input an array, and produces as
@@ -1311,6 +1311,9 @@ sections:
13111311
13121312
If the input is an empty array, `add` returns `null`.
13131313
1314+
`add(generator)` operates on the given generator rather than
1315+
the input.
1316+
13141317
examples:
13151318
- program: add
13161319
input: '["a","b","c"]'
@@ -1321,6 +1324,9 @@ sections:
13211324
- program: add
13221325
input: '[]'
13231326
output: ["null"]
1327+
- program: add(.[].a)
1328+
input: '[{"a":3}, {"a":5}, {"b":6}]'
1329+
output: ['8']
13241330

13251331
- title: "`any`, `any(condition)`, `any(generator; condition)`"
13261332
body: |

jq.1.prebuilt

Lines changed: 9 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/builtin.jq

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@ def unique: group_by(.) | map(.[0]);
88
def unique_by(f): group_by(f) | map(.[0]);
99
def max_by(f): _max_by_impl(map([f]));
1010
def min_by(f): _min_by_impl(map([f]));
11-
def add: reduce .[] as $x (null; . + $x);
11+
def add(f): reduce f as $x (null; . + $x);
12+
def add: add(.[]);
1213
def del(f): delpaths([path(f)]);
1314
def abs: if . < 0 then - . else . end;
1415
def _assign(paths; $value): reduce path(paths) as $p (.; setpath($p; $value));

tests/jq.test

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -642,6 +642,19 @@ map_values(.+1)
642642
[0,1,2]
643643
[1,2,3]
644644

645+
[add(null), add(range(range(10))), add(empty), add(10,range(10))]
646+
null
647+
[null,120,null,55]
648+
649+
# Real-world use case for add(empty)
650+
.sum = add(.arr[])
651+
{"arr":[]}
652+
{"arr":[],"sum":null}
653+
654+
add({(.[]):1}) | keys
655+
["a","a","b","a","d","b","d","a","d"]
656+
["a","b","d"]
657+
645658
#
646659
# User-defined functions
647660
# Oh god.

tests/man.test

Lines changed: 4 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)