Skip to content
Myr

Make first(g) more efficient: extract only 1 value

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

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.

authored by Nicolas Williams · committed by Nicolas Williams · parent e24af3c · Browse files · 2 files+6 added−1 removed
This commit

State

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

Diff stats

2 files+6 added−1 removed

  • tests:+5 added−0 removed
  • other:+1 added−1 removed

2 files+6 added−1 removed

modified:src/builtin.jq+1 added-1 removed
165 unmodified lines
166 def _until:167 if cond then . else (next|_until) end;168 _until;169def 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;170def first(g): label $out | foreach g as $item ([false, null]; if .[0]==true then break $out else [true, $item] end; .[1]);170def first(g): label $out | g | ., break $out;171def last(g): reduce g as $item (null; $item);172def nth($n; g): if $n < 0 then error("nth doesn't support negative indices") else last(limit($n + 1; g)) end;173def first: .[0];174def last: .[-1];
115 unmodified lines
modified:tests/jq.test+5 added
301 unmodified lines
302[first(range(.)), last(range(.)), nth(0; range(.)), nth(5; range(.)), try nth(-1; range(.)) catch .]30310304[0,9,0,5,"nth doesn't support negative indices"]305306# Check that first(g) does not extract more than one value from g307first(1,error("foo"))308null3091310311#312# Check that various builtins evalute all arguments where appropriate,313# doing cartesian products where appropriate.314#
1010 unmodified lines