summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMuh Muhten <muh.muhten@gmail.com>2019-02-26 05:40:01 -0500
committerNico Williams <nico@cryptonector.com>2019-02-26 11:05:25 -0600
commita1626adb7ec90f19e57f24eafefb7b1bdb518e7d (patch)
tree85f118d6cfbb2e50ac3594df2a1388439ed504c8
parentd1a07cbdc1363bf2f8846fa5c84a81c6e95435d4 (diff)
Fix bizarre bsearch/1 behaviour with a stream argument
-rw-r--r--src/builtin.jq10
-rw-r--r--tests/jq.test4
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