Skip to content

Commit e2e995a

Browse files
Duologicjohnbartholomew
authored andcommitted
feat: allow negative index/end on std.slice
1 parent deac98c commit e2e995a

File tree

2 files changed

+47
-7
lines changed

2 files changed

+47
-7
lines changed

stdlib/std.jsonnet

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -208,18 +208,27 @@ limitations under the License.
208208
{
209209
indexable: indexable,
210210
index:
211-
if index == null then 0
212-
else index,
211+
if index == null
212+
then 0
213+
else
214+
if index < 0
215+
then std.length(indexable) + index
216+
else index,
213217
end:
214-
if end == null then std.length(indexable)
215-
else end,
218+
if end == null
219+
then std.length(indexable)
220+
else
221+
if end < 0
222+
then std.length(indexable) + end
223+
else end,
216224
step:
217-
if step == null then 1
225+
if step == null
226+
then 1
218227
else step,
219228
length: std.length(indexable),
220229
type: std.type(indexable),
221230
};
222-
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];
231+
assert invar.step >= 0 : 'got [%s:%s:%s] but negative steps are not supported' % [invar.index, invar.end, invar.step];
223232
assert step != 0 : 'got %s but step must be greater than 0' % step;
224233
assert std.isString(indexable) || std.isArray(indexable) : 'std.slice accepts a string or an array, but got: %s' % std.type(indexable);
225234
local build(slice, cur) =

test_suite/slice.sugar.jsonnet

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,22 @@ local arrCases = [
9292
input: (arr)[2:1000],
9393
output: [2, 3, 4, 5],
9494
},
95-
95+
{
96+
input: arr[-2:],
97+
output: [4, 5],
98+
},
99+
{
100+
input: arr[:-3],
101+
output: [0, 1, 2],
102+
},
103+
{
104+
input: arr[-3:-1],
105+
output: [3, 4],
106+
},
107+
{
108+
input: arr[-1:-1],
109+
output: [],
110+
},
96111
];
97112

98113
local strCases = [
@@ -168,6 +183,22 @@ local strCases = [
168183
input: (str)[2:1000],
169184
output: '2345',
170185
},
186+
{
187+
input: str[-2:],
188+
output: '45',
189+
},
190+
{
191+
input: str[:-3],
192+
output: '012',
193+
},
194+
{
195+
input: str[-3:-1],
196+
output: '34',
197+
},
198+
{
199+
input: str[-1:-1],
200+
output: '',
201+
},
171202
];
172203

173204
std.foldl(

0 commit comments

Comments
 (0)