}
}
{
+ // Note that we can now define `range` as a jq-coded function
block rangevar = gen_op_var_fresh(STOREV, "rangevar");
block init = BLOCK(gen_op_simple(DUP), gen_call("start", gen_noop()), rangevar);
block range = BLOCK(init,
"def test(re; mode): _match_impl(re; mode; true);",
"def test(val): if val |type == \"string\" then test(val; null) elif val | type == \"array\" and (val | length) > 1 then test(val[0]; val[1]) elif val | type == \"array\" and (val | length > 0) then test(val[0]; null) else error((val | type) + \" not a string or array\") end;",
// "def test(re): _match(re; null; 1);",
-
+ // 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));",
};
#undef LIBM_DD
input: '[{"foo": "bar"}, [{"foo": "baz"}]]'
output: ['[{"foo": "bar"}, {"foo": "baz"}]']
- - title: "`range(upto)`, `range(from;upto)`"
+ - title: "`range(upto)`, `range(from;upto)` `range(from;upto;by)`"
body: |
The `range` function produces a range of numbers. `range(4;10)`
are produced as separate outputs. Use `[range(4;10)]` to get a range as
an array.
- Its first argument can be omitted; it defaults to zero.
+ The one argument form generates numbers from 0 to the given
+ number, with an increment of 1.
+
+ The two argument form generates numbers from `from` to `upto`
+ with an increment of 1.
+
+ The three argument form generates numbers `from` to `upto`
+ with an increment of `by`.
examples:
- program: 'range(2;4)'
- program: '[range(4)]'
input: 'null'
output: ['[0,1,2,3]']
+ - program: '[range(0;10;3)]'
+ input: 'null'
+ output: ['[0,3,6,9]']
+ - program: '[range(0;10;-1)]'
+ input: 'null'
+ output: ['[]']
+ - program: '[range(0;-5;-1)]'
+ input: 'null'
+ output: ['[0,-1,-2,-3,-4]']
- title: "`floor`"
body: |
then ., ((.+by)|_range)
else . end;
if by == 0 then init else init|_range end |
- select(. < upto);
+ select((by > 0 and . < upto) or (by < 0 and . > upto));
range(0; 10; 3)'
input: 'null'
output: ['0,3,6,9']