Add step to slice notation
nlepage opened this issue · comments
Description
Add step to the slice notation in order to conform to the ES slice notation: array[start:end:step]
.
Like start
and end
, step
may be negative.
This doesn't change the fact that start
is inclusive and end
is exclusive.
When step
is negative, start
should be greater than end
, otherwise slice will be empty.
When step
is negative, implicit start
becomes length - 1
and implicit (exclusive) end
becomes -1
.
Examples
Update even elements with step of 2
multiply(
{ nested: { prop: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] } },
'nested.prop[::2]',
100,
)
// returns { nested: { prop: [0, 1, 200, 3, 400, 5, 600, 7, 800, 9] } }
Fetch reversed slice with step of -1
get(
{ nested: { prop: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] } },
'nested.prop[3::-1]'
)
// returns [3, 2, 1, 0]
Clarifying example with negative step
const obj = { nested: { prop: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] } }
get(obj, 'nested.prop[1:3:-1]') // returns []
get(obj, 'nested.prop[3:1:-1]') // returns [3, 2]
Waitin for #327
So I posted an issue on the tc39 proposal to validate this:
Like
start
andend
,step
may be negative.
This doesn't change the fact thatstart
is inclusive andend
is exclusive.
Whenstep
is negative, implicitstart
becomeslength - 1
and implicit (exclusive)end
becomes-1
.