Remove by reverse index range

I’m currently using a sorted map with a timestamp as a key, and trying to enforce a limit using an atomic map operation, keeping the most recent items. Unfortunately there doesn’t seem to be a way to keep only last X elements in a sorted map. What I have done as a workaround is to use negative timestamp as the key, and then use removeByIndexRange.

It would be nice if there was either a way to set the sort ordering (e.g. ASCENDING, DESCENDING), or to allow negative indexes to be used by removeByIndexRange for this purpose, or a new method (e.g. removeByReverseIndexRange). Any of these options would allow for limit on last X items without changing the map key.

There may be an invert selection feature later.

The current way to do this is by using negative index notation. In negative index notation, -1 refers to the last element and -2 refers to the 2nd to the last. They can also go beyond the first element. If you had a list [0, 1, 2, 3], INDEX_RANGE(index=-6, count=4) refer to [0, 1].

For example: Let X be what you want to keep (e.g. X = 100). REMOVE_BY_INDEX_RANGE(-10 * X, 9 * X) will let you keep the top X items provided the list doesn’t grow beyond 10 * X before you prune. You can control the limit, i.e. use (-100 * X, 99 * X).

If you want to control the limit via a const value: Let be the growth limit (e.g. Y = 1000000). REMOVE_BY_INDEX_RANGE(-Y, Y - X) is the form you need.

It’s not as nice as invert select, but works as long as the map doesn’t grow beyond Y before pruning and is available right now.

1 Like

Interesting that it can be done (with some constraints) using removeByIndexRange and negative numbers, but it does make the code confusing to read. The invert selection and sort ordering would still be nice features to have.

INVERTED flag was implemented as of version 3.16 along with many additional functions for list. We recommend the 4.0+ though, as 3.16 isn’t getting anymore hot fixes.

This topic was automatically closed 6 days after the last reply. New replies are no longer allowed.