Request for suggestions: Support negative integers in the `slice` filter
Nobody has claimed this yet.
- Dominant language
- Ruby
- Stars
- 11.9k
- Forks
- 1.5k
- Avg merge
- 17h 55m
- Merged PRs (30d)
- 3
Description
Author: Shopify
Expected end date: December 5, 2024
Background
Today, the slice filter is limited to counting items from the start index, with no option to count backwards from the end. This creates unnecessary toil, affecting the developer experience, as seen in the following examples.
It's straightforward counting from the index:
{% assign fruits = 'apple, banana, cherry, tomato, fig' | split: ", " %}
{{ fruits | slice: 1, 3 }}
{% # => [ "banana", "cherry", "tomato" ] %}
However, operations such as getting all array elements except the last two can become verbose:
{% assign end_index = fruits.size | minus: 2 %}
{{ fruits | slice: 0, end_index }}
{% # => [ "apple", "banana", "cherry" ] %}
Proposal
Inspired by slice operations in other languages, we propose supporting negative numbers in the second argument, making operations more intuitive by controlling the direction of elements being taken.
With this enhancement, that example becomes simpler and clearer:
{{ fruits | slice: 0, -2 }}
{% # => [ "apple", "banana", "cherry" ] %}
Here's how the negative number influences the direction of the second argument:
{{ fruits | slice: 1, 3 }}
{{ fruits | slice: 1, -3 }}
Limitations
This proposal is not currently backward compatible:
{{ fruits | slice: 0, -2 }}
{% # => [] %}
Therefore, we will conduct an impact assessment to evaluate the feasibility and ensure a smooth transition if this change is implemented.
Call for suggestions
We welcome any feedback or opinions on this proposal. Please share your thoughts by December 5, 2024. Your input is valuable as we prepare to begin active development on this initiative.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reviewing the proposed negative-integer behavior for the slice filter and the stated backward-compatibility limitation. Assess the impact on existing uses, resolve the semantics for negative arguments, and treat the work as done only when the feasibility and transition approach are established.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- ruby
- Domain
- developer-experience
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100