From a1626adb7ec90f19e57f24eafefb7b1bdb518e7d Mon Sep 17 00:00:00 2001 From: Muh Muhten Date: Tue, 26 Feb 2019 05:40:01 -0500 Subject: Fix bizarre bsearch/1 behaviour with a stream argument --- src/builtin.jq | 10 +++++----- tests/jq.test | 4 +++- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/builtin.jq b/src/builtin.jq index f45802f6..321358c6 100644 --- a/src/builtin.jq +++ b/src/builtin.jq @@ -224,10 +224,10 @@ def tostream: # the index of the target if the target is in the input array; and otherwise # (-1 - ix), where ix is the insertion point that would leave the array sorted. # If the input is not sorted, bsearch will terminate but with irrelevant results. -def bsearch(target): +def bsearch($target): if length == 0 then -1 elif length == 1 then - if target == .[0] then 0 elif target < .[0] then -1 else -2 end + if $target == .[0] then 0 elif $target < .[0] then -1 else -2 end else . as $in # state variable: [start, end, answer] # where start and end are the upper and lower offsets to use. @@ -237,14 +237,14 @@ def bsearch(target): else ( ( (.[1] + .[0]) / 2 ) | floor ) as $mid | $in[$mid] as $monkey - | if $monkey == target then (.[2] = $mid) # success + | if $monkey == $target then (.[2] = $mid) # success elif .[0] == .[1] then (.[1] = -1) # failure - elif $monkey < target then (.[0] = ($mid + 1)) + elif $monkey < $target then (.[0] = ($mid + 1)) else (.[1] = ($mid - 1)) end end ) | if .[2] == null then # compute the insertion point - if $in[ .[0] ] < target then (-2 -.[0]) + if $in[ .[0] ] < $target then (-2 -.[0]) else (-1 -.[0]) end else .[2] diff --git a/tests/jq.test b/tests/jq.test index 539ee7d8..b85f897d 100644 --- a/tests/jq.test +++ b/tests/jq.test @@ -1427,8 +1427,10 @@ ascii_upcase "useful but not for é" "USEFUL BUT NOT FOR é" -bsearch(4) +bsearch(0,2,4) [1,2,3] +-1 +1 -4 # strptime tests are in optional.test -- cgit v1.2.3