Skip to content

Commit

Permalink
feat: allow negative index/end on std.slice
Browse files Browse the repository at this point in the history
  • Loading branch information
Duologic committed Jun 1, 2023
1 parent 6fc4aec commit e9a2fb3
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 7 deletions.
21 changes: 15 additions & 6 deletions stdlib/std.jsonnet
Original file line number Diff line number Diff line change
Expand Up @@ -206,18 +206,27 @@ limitations under the License.
{
indexable: indexable,
index:
if index == null then 0
else index,
if index == null
then 0
else
if index < 0
then std.length(indexable) + index
else index,
end:
if end == null then std.length(indexable)
else end,
if end == null
then std.length(indexable)
else
if end < 0
then std.length(indexable) + end
else end,
step:
if step == null then 1
if step == null
then 1
else step,
length: std.length(indexable),
type: std.type(indexable),
};
assert invar.index >= 0 && invar.end >= 0 && invar.step >= 0 : 'got [%s:%s:%s] but negative index, end, and steps are not supported' % [invar.index, invar.end, invar.step];
assert invar.step >= 0 : 'got [%s:%s:%s] but negative steps are not supported' % [invar.index, invar.end, invar.step];
assert step != 0 : 'got %s but step must be greater than 0' % step;
assert std.isString(indexable) || std.isArray(indexable) : 'std.slice accepts a string or an array, but got: %s' % std.type(indexable);
local build(slice, cur) =
Expand Down
33 changes: 32 additions & 1 deletion test_suite/slice.sugar.jsonnet
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,22 @@ local arrCases = [
input: (arr)[2:1000],
output: [2, 3, 4, 5],
},

{
input: arr[-2:],
output: [4, 5],
},
{
input: arr[:-3],
output: [0, 1, 2],
},
{
input: arr[-3:-1],
output: [3, 4],
},
{
input: arr[-1:-1],
output: [],
},
];

local strCases = [
Expand Down Expand Up @@ -168,6 +183,22 @@ local strCases = [
input: (str)[2:1000],
output: '2345',
},
{
input: str[-2:],
output: '45',
},
{
input: str[:-3],
output: '012',
},
{
input: str[-3:-1],
output: '34',
},
{
input: str[-1:-1],
output: '',
},
];

std.foldl(
Expand Down

0 comments on commit e9a2fb3

Please sign in to comment.