Skip to content
Myr

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

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by itchyny · committed by Nico Williams · parent e2bc8de · Browse files · 3 files+11 added−7 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+11 added−7 removed

  • tests:+6 added−2 removed
  • other:+5 added−5 removed

3 files+11 added−7 removed

modified:docs/content/manual/manual.yml+2 added-4 removed
2830 unmodified lines
28312832 The `first(expr)` and `last(expr)` functions extract the first2833 and last values from `expr`, respectively.28342835 The `nth(n; expr)` function extracts the nth value output by2836 `expr`. This can be defined as `def nth(n; expr):2837 last(limit(n + 1; expr));`. Note that `nth(n; expr)` doesn't2838 support negative values of `n`.2835 The `nth(n; expr)` function extracts the nth value output by `expr`.2836 Note that `nth(n; expr)` doesn't support negative values of `n`.28372838 examples:2839 - program: '[first(range(.)), last(range(.)), nth(./2; range(.))]'2840 input: '10'
616 unmodified lines
modified:src/builtin.jq+3 added-1 removed
161 unmodified lines
162def any(condition): any(.[]; condition);163def all: all(.[]; .);164def any: any(.[]; .);165def last(g): reduce g as $item (null; $item);166def nth($n; g): if $n < 0 then error("nth doesn't support negative indices") else last(limit($n + 1; g)) end;166def nth($n; g):167 if $n < 0 then error("nth doesn't support negative indices")168 else label $out | foreach g as $item ($n + 1; . - 1; if . <= 0 then $item, break $out else empty end) end;169def first: .[0];170def last: .[-1];171def nth($n): .[$n];172def combinations:
108 unmodified lines
modified:tests/jq.test+6 added-2 removed
317 unmodified lines
318[limit(1; 1, error)]319"badness"320[1]321322[first(range(.)), last(range(.)), nth(0; range(.)), nth(5; range(.)), try nth(-1; range(.)) catch .]322[first(range(.)), last(range(.))]32310324[0,9,0,5,"nth doesn't support negative indices"]324[0,9]325326[nth(0,5,9,10,15; range(.)), try nth(-1; range(.)) catch .]32710328[0,5,9,"nth doesn't support negative indices"]329330# Check that first(g) does not extract more than one value from g331first(1,error("foo"))332null3331
1434 unmodified lines