Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix nth/2 to emit empty on index out of range #2674

Merged
merged 1 commit into from
Jul 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Fix nth/2 to emit empty on index out of range
  • Loading branch information
itchyny committed Jul 9, 2023
commit 8e86424147b103b50aee3f0a750bc840b006c9e1
6 changes: 2 additions & 4 deletions docs/content/manual/manual.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2832,10 +2832,8 @@ sections:
The `first(expr)` and `last(expr)` functions extract the first
and last values from `expr`, respectively.

The `nth(n; expr)` function extracts the nth value output by
`expr`. This can be defined as `def nth(n; expr):
last(limit(n + 1; expr));`. Note that `nth(n; expr)` doesn't
support negative values of `n`.
The `nth(n; expr)` function extracts the nth value output by `expr`.
Note that `nth(n; expr)` doesn't support negative values of `n`.

examples:
- program: '[first(range(.)), last(range(.)), nth(./2; range(.))]'
Expand Down
4 changes: 3 additions & 1 deletion src/builtin.jq
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,9 @@ def any(condition): any(.[]; condition);
def all: all(.[]; .);
def any: any(.[]; .);
def last(g): reduce g as $item (null; $item);
def nth($n; g): if $n < 0 then error("nth doesn't support negative indices") else last(limit($n + 1; g)) end;
def nth($n; g):
if $n < 0 then error("nth doesn't support negative indices")
else label $out | foreach g as $item ($n + 1; . - 1; if . <= 0 then $item, break $out else empty end) end;
def first: .[0];
def last: .[-1];
def nth($n): .[$n];
Expand Down
8 changes: 6 additions & 2 deletions tests/jq.test
Original file line number Diff line number Diff line change
Expand Up @@ -319,9 +319,13 @@ null
"badness"
[1]

[first(range(.)), last(range(.)), nth(0; range(.)), nth(5; range(.)), try nth(-1; range(.)) catch .]
[first(range(.)), last(range(.))]
10
[0,9,0,5,"nth doesn't support negative indices"]
[0,9]

[nth(0,5,9,10,15; range(.)), try nth(-1; range(.)) catch .]
10
[0,5,9,"nth doesn't support negative indices"]

# Check that first(g) does not extract more than one value from g
first(1,error("foo"))
Expand Down