stringtemplate4 icon indicating copy to clipboard operation
stringtemplate4 copied to clipboard

Feature request: limit arrays

Open yuraj11 opened this issue 6 years ago • 3 comments

Is there any way to limit arrays ? Something like this would be useful: <myobj.items:{it|<it.something>}; limit=10 >

yuraj11 avatar Mar 02 '18 14:03 yuraj11

Ok I have found a workaround for this:

group.defineDictionary("max", new MaxListItemsLimiter());

Usage (first item is always max. items count, second is List): <max.(["50",myObject.items]):{msg|<msg.something>}>

final class MaxListItemsLimiter extends AbstractMap<String, Object> {

    @Override
    public Object get(Object key) {
        List items = (List) key;
        if (!items.isEmpty()) {
            //First item is max. count
            Integer limit = NumberUtils.toInt(items.get(0).toString(), -1); //use Integer.parseInt
            if (limit != -1) {
                return items.subList(1, Math.min(items.size(), limit + 1));
            } else {
                throw new AssertionError("First parameter in max must be number");
            }
        } else {
            return super.get(key);
        }
    }

    @Override
    public Set<Map.Entry<String, Object>> entrySet() {
        return Collections.emptySet();
    }

    @Override
    public boolean containsKey(Object key) {
        if (key instanceof List) {
            return true;
        } else {
            throw new AssertionError("You can use max only on Lists.");
        }
    }
}

yuraj11 avatar Mar 06 '18 07:03 yuraj11

Not a bad idea to have. thanks for the suggestion.

parrt avatar Nov 08 '18 19:11 parrt

What is the use case? Pagination comes to mind, but that also requires a way to skip n items.

Clashsoft avatar Jun 30 '20 14:06 Clashsoft