From 396543191cec32f69712b4364d26a0ebaa61b801 Mon Sep 17 00:00:00 2001 From: Nicolas Williams Date: Fri, 27 Jan 2017 09:48:13 -0600 Subject: [PATCH] Make first(g) more efficient: extract only 1 value first(g) was extracting two values, which, if g is slow, made first(g) slow. And if the second extraction were to throw an error, then first(g) would throw that error, which is clearly not the right thing to do. Besides that, first(g) was allocating garbage, which it no longer does. --- src/builtin.jq | 2 +- tests/jq.test | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/builtin.jq b/src/builtin.jq index 53998a85..9f6e656c 100644 --- a/src/builtin.jq +++ b/src/builtin.jq @@ -167,7 +167,7 @@ def until(cond; next): if cond then . else (next|_until) end; _until; def limit($n; exp): if $n < 0 then exp else label $out | foreach exp as $item ([$n, null]; if .[0] < 1 then break $out else [.[0] -1, $item] end; .[1]) end; -def first(g): label $out | foreach g as $item ([false, null]; if .[0]==true then break $out else [true, $item] end; .[1]); +def first(g): label $out | g | ., break $out; 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]; diff --git a/tests/jq.test b/tests/jq.test index fc92d35b..302952d5 100644 --- a/tests/jq.test +++ b/tests/jq.test @@ -303,6 +303,11 @@ null 10 [0,9,0,5,"nth doesn't support negative indices"] +# Check that first(g) does not extract more than one value from g +first(1,error("foo")) +null +1 + # # Check that various builtins evalute all arguments where appropriate, # doing cartesian products where appropriate.