Skip to content

feat(slice): support negative steps like [::-1] - #288

Merged
brettz9 merged 1 commit into
JSONPath-Plus:mainfrom
simonkundrik:feat/slice-negative-step
Nov 3, 2026
Merged

brettz9 merged 1 commit into
JSONPath-Plus:mainfrom
simonkundrik:feat/slice-negative-step

Conversation

@simonkundrik

Copy link
Copy Markdown
Contributor

Fixes #176.

$[::-1] and any other slice with a negative step returned nothing. Two things were in the way. The regex that routes [start:end:step] to the slice code only allowed digits for the step, so [::-1] was never treated as a slice. And _slice only walked forwards. A step of 0 was also silently turned into 1, so $[1:2:0] returned item 1.

Slices now follow RFC 9535 section 2.3.4.2.2:

  • A negative step walks backwards. The defaults are the last item for the start and the first item (included) for the end, and the bounds are clamped the way the RFC describes, so very large or very small numbers work too.
  • A step of 0 selects nothing.
  • Positive steps behave exactly as before.

I found it by running the official JSONPath compliance test suite for RFC 9535 against the library. Every one of the 14 failing slice cases in it was a negative step or a zero step, and all of them pass now (the other slice cases already did). The rest of the suite fails mostly on things this library does differently on purpose (?@.a without parentheses, the function extensions, and so on), so I left those alone.

Tests: 16 new ones in test.slice.js, the 14 compliance cases (13 negative steps, plus one that was already fine), reversing objects with resultType: 'path', and the zero step. 15 of them fail without the change and all pass with it.

Checks: eslint, tsc and the c8 coverage check (100%) pass locally. On my machine (Windows) the two cli tests fail both with and without this change, because bin isn't found by the shell they spawn, so I'm relying on CI for those. I didn't run the rollup build.

The slice selector only handled a positive step: the check that routes
[start:end:step] to _slice allowed only digits after the second colon, so
[::-1] never reached it, and a step of 0 was silently turned into 1.

Slices now follow RFC 9535 section 2.3.4.2.2. A negative step walks
backwards, with the last item as the default start and the first item as
the default end, and a step of 0 selects nothing. Positive steps behave as
before.

Fixes JSONPath-Plus#176

@brettz9 brettz9 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks!

@brettz9
brettz9 merged commit c859500 into JSONPath-Plus:main Nov 3, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Slice Selector for reversing the Output

2 participants