Skip to content

Commit

Permalink
Implement add/1 (#3144)
Browse files Browse the repository at this point in the history
  • Loading branch information
myaaaaaaaaa authored Aug 20, 2024
1 parent 137018d commit 0b5ae30
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 4 deletions.
8 changes: 7 additions & 1 deletion docs/content/manual/dev/manual.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1300,7 +1300,7 @@ sections:
input: '[1,[[],{"a":2}]]'
output: ['[[0],[1,1,"a"]]']

- title: "`add`"
- title: "`add`, `add(generator)`"
body: |
The filter `add` takes as input an array, and produces as
Expand All @@ -1311,6 +1311,9 @@ sections:
If the input is an empty array, `add` returns `null`.
`add(generator)` operates on the given generator rather than
the input.
examples:
- program: add
input: '["a","b","c"]'
Expand All @@ -1321,6 +1324,9 @@ sections:
- program: add
input: '[]'
output: ["null"]
- program: add(.[].a)
input: '[{"a":3}, {"a":5}, {"b":6}]'
output: ['8']

- title: "`any`, `any(condition)`, `any(generator; condition)`"
body: |
Expand Down
11 changes: 9 additions & 2 deletions jq.1.prebuilt

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion src/builtin.jq
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ def unique: group_by(.) | map(.[0]);
def unique_by(f): group_by(f) | map(.[0]);
def max_by(f): _max_by_impl(map([f]));
def min_by(f): _min_by_impl(map([f]));
def add: reduce .[] as $x (null; . + $x);
def add(f): reduce f as $x (null; . + $x);
def add: add(.[]);
def del(f): delpaths([path(f)]);
def abs: if . < 0 then - . else . end;
def _assign(paths; $value): reduce path(paths) as $p (.; setpath($p; $value));
Expand Down
13 changes: 13 additions & 0 deletions tests/jq.test
Original file line number Diff line number Diff line change
Expand Up @@ -642,6 +642,19 @@ map_values(.+1)
[0,1,2]
[1,2,3]

[add(null), add(range(range(10))), add(empty), add(10,range(10))]
null
[null,120,null,55]

# Real-world use case for add(empty)
.sum = add(.arr[])
{"arr":[]}
{"arr":[],"sum":null}

add({(.[]):1}) | keys
["a","a","b","a","d","b","d","a","d"]
["a","b","d"]

#
# User-defined functions
# Oh god.
Expand Down
4 changes: 4 additions & 0 deletions tests/man.test

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 0b5ae30

Please sign in to comment.