mirror of
https://github.com/stedolan/jq.git
synced 2024-05-11 05:55:39 +00:00
Add first
, nth
, last
(fix #510)
This commit is contained in:
@ -986,6 +986,12 @@ static const char* const jq_builtins[] = {
|
||||
" if cond then ., (update | _while) else empty end; "
|
||||
" try _while catch if .==\"break\" then empty else . end;",
|
||||
"def limit(n; exp): if n < 0 then exp else foreach exp as $item ([n, null]; if .[0] < 1 then break else [.[0] -1, $item] end; .[1]) end;",
|
||||
"def first(g): foreach g as $item ([false, null]; if .[0]==true then break else [true, $item] end; .[1]);",
|
||||
"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 first: .[0];",
|
||||
"def last: .[-1];",
|
||||
"def nth(n): .[n];",
|
||||
};
|
||||
#undef LIBM_DD
|
||||
|
||||
|
@ -1835,6 +1835,35 @@ sections:
|
||||
input: '[0,1,2,3,4,5,6,7,8,9]'
|
||||
output: ['[0,1,2]']
|
||||
|
||||
- title: "`first(expr)`, `last(expr)`, `nth(n; expr)`"
|
||||
body: |
|
||||
|
||||
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`.
|
||||
|
||||
examples:
|
||||
- program: '[first(range(.)), last(range(.)), nth(./2; range(.))]'
|
||||
input: '10'
|
||||
output: ['[0,9,4]']
|
||||
|
||||
- title: "`first`, `last`, `nth(n)`"
|
||||
body: |
|
||||
|
||||
The `first` and `last` functions extract the first
|
||||
and last values from any array at `.`.
|
||||
|
||||
The `nth(n)` function extracts the nth value of any array at `.`.
|
||||
|
||||
examples:
|
||||
- program: '[range(.)]|[first, last, nth(5)]'
|
||||
input: '10'
|
||||
output: ['[0,9,5]']
|
||||
|
||||
- title: "`foreach`"
|
||||
body: |
|
||||
|
||||
|
@ -242,6 +242,10 @@ null
|
||||
[11,22,33,44,55,66,77,88,99]
|
||||
[11,22,33]
|
||||
|
||||
[first(range(.)), last(range(.)), nth(0; range(.)), nth(5; range(.)), try nth(-1; range(.)) catch .]
|
||||
10
|
||||
[0,9,0,5,"nth doesn't support negative indices"]
|
||||
|
||||
#
|
||||
# Slices
|
||||
#
|
||||
|
Reference in New Issue
Block a user