Skip to content

Commit

Permalink
implement skip/2, fix limit/2 to emit error on negative count
Browse files Browse the repository at this point in the history
  • Loading branch information
itchyny committed Oct 5, 2024
1 parent c91bf50 commit 086bd2b
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 11 deletions.
5 changes: 3 additions & 2 deletions builtin.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 15 additions & 8 deletions builtin.jq
Original file line number Diff line number Diff line change
Expand Up @@ -77,19 +77,26 @@ def limit($n; g):
elif $n == 0 then
empty
else
error("limit doesn't support negative count")
end;
def skip($n; g):
if $n > 0 then
foreach g as $item (
$n;
. - 1;
if . < 0 then $item else empty end
)
elif $n == 0 then
g
else
error("skip doesn't support negative count")
end;
def nth($n): .[$n];
def nth($n; g):
if $n < 0 then
error("nth doesn't support negative indices")
if $n >= 0 then
first(skip($n; g))
else
label $out |
foreach g as $item (
$n + 1;
. - 1;
if . <= 0 then $item, break $out else empty end
)
error("nth doesn't support negative index")
end;

def truncate_stream(f):
Expand Down
40 changes: 39 additions & 1 deletion cli/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4053,7 +4053,23 @@
- 'nth(-1;.[])'
input: '[]'
error: |
error: nth doesn't support negative indices
error: nth doesn't support negative index
- name: nth/2 function with infinite range
args:
- 'nth(range(3); range(infinite))'
input: 'null'
expected: |
0
1
2
- name: nth/2 function with error
args:
- 'nth(1; 0,1,error)'
input: 'null'
expected: |
1
- name: all/2 function in first/1 argument
args:
Expand All @@ -4070,6 +4086,28 @@
expected: |
[0,1,2,0,1,2,3,4,5,6,7,8,9,10,11,12]
- name: limit/2 function with negative count
args:
- 'limit(-1; range(3))'
input: 'null'
error: |
limit doesn't support negative count
- name: skip/2 function
args:
- -c
- '[skip(0,3,5,7; range(5))]'
input: 'null'
expected: |
[0,1,2,3,4,3,4]
- name: skip/2 function with negative count
args:
- 'skip(-1; range(3))'
input: 'null'
error: |
skip doesn't support negative count
- name: all/0, any/0 functions
args:
- -c
Expand Down

0 comments on commit 086bd2b

Please sign in to comment.