summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authoritchyny <itchyny@cybozu.co.jp>2023-07-09 12:56:59 +0900
committerNico Williams <nico@cryptonector.com>2023-07-08 23:13:15 -0500
commitd8072564c28d38d29aa0a7c416621f02c19f7f44 (patch)
tree47e98bb8a510f15d927b3e0ea50d292881e009d9
parente2bc8de8bb0487e9ae9f8d8203cf4988154ba3f0 (diff)
Fix nth/2 to emit empty on index out of range
-rw-r--r--docs/content/manual/manual.yml6
-rw-r--r--src/builtin.jq4
-rw-r--r--tests/jq.test8
3 files changed, 11 insertions, 7 deletions
diff --git a/docs/content/manual/manual.yml b/docs/content/manual/manual.yml
index 30b0cf60..183e4a5d 100644
--- a/docs/content/manual/manual.yml
+++ b/docs/content/manual/manual.yml
@@ -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(.))]'
diff --git a/src/builtin.jq b/src/builtin.jq
index aac22cb7..146a64a3 100644
--- a/src/builtin.jq
+++ b/src/builtin.jq
@@ -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];
diff --git a/tests/jq.test b/tests/jq.test
index 193025da..4e693452 100644
--- a/tests/jq.test
+++ b/tests/jq.test
@@ -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"))