summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMuh Muhten <muh.muhten@gmail.com>2019-02-26 05:22:18 -0500
committerNico Williams <nico@cryptonector.com>2019-02-26 11:05:25 -0600
commitfc6df0fdc1a130575e3f2074cae56e221cca7038 (patch)
treeb732551100f81edd593c8792981ced741e8ee650
parent78271b179a125bc2a4b38479e03314157d3319e6 (diff)
Simplify definition of range/3
New implementation in terms of while/2, and branches immediately on $by to avoid checking the sign of $by *in* the loop.
-rw-r--r--src/builtin.jq10
1 files changed, 5 insertions, 5 deletions
diff --git a/src/builtin.jq b/src/builtin.jq
index 2c7bebeb..6b092bc0 100644
--- a/src/builtin.jq
+++ b/src/builtin.jq
@@ -138,11 +138,6 @@ def gsub($re; s; flags): sub($re; s; flags + "g");
def gsub($re; s): sub($re; s; "g");
########################################################################
-# range/3, with a `by` expression argument
-def range($init; $upto; $by):
- def _range:
- if ($by > 0 and . < $upto) or ($by < 0 and . > $upto) then ., ((.+$by)|_range) else . end;
- if $by == 0 then $init else $init|_range end | select(($by > 0 and . < $upto) or ($by < 0 and . > $upto));
# generic iterator/generator
def while(cond; update):
def _while:
@@ -156,6 +151,11 @@ def limit($n; exp):
if $n > 0 then label $out | foreach exp as $item ($n; .-1; $item, if . <= 0 then break $out else empty end)
elif $n == 0 then empty
else exp end;
+# range/3, with a `by` expression argument
+def range($init; $upto; $by):
+ if $by > 0 then $init|while(. < $upto; . + $by)
+ elif $by < 0 then $init|while(. > $upto; . + $by)
+ else empty end;
def first(g): label $out | g | ., break $out;
def isempty(g): first((g|false), true);
def all(generator; condition): isempty(generator|condition and empty);