From: Nicolas Williams Date: Mon, 28 Jul 2014 18:18:58 +0000 (-0500) Subject: Add `first`, `nth`, `last` (fix #510) X-Git-Tag: jq-1.5rc1~105 X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=e1b20b48f04a1225cd4d541500c1b00eb89a1a78;p=jq Add `first`, `nth`, `last` (fix #510) --- diff --git a/builtin.c b/builtin.c index 0af4416..dea5fbb 100644 --- a/builtin.c +++ b/builtin.c @@ -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 diff --git a/docs/content/3.manual/manual.yml b/docs/content/3.manual/manual.yml index c5a3cbe..bd34385 100644 --- a/docs/content/3.manual/manual.yml +++ b/docs/content/3.manual/manual.yml @@ -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: | diff --git a/tests/all.test b/tests/all.test index 3685a0e..778606a 100644 --- a/tests/all.test +++ b/tests/all.test @@ -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 #