antlr / stringtemplate4

StringTemplate 4
http://www.stringtemplate.org
Other
955 stars 231 forks source link

Feature request: limit arrays #197

Open yuraj11 opened 6 years ago

yuraj11 commented 6 years ago

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

yuraj11 commented 6 years ago

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.");
        }
    }
}
parrt commented 6 years ago

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

Clashsoft commented 4 years ago

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