feat: add filter() macro for array filtering#384
feat: add filter() macro for array filtering#384sheshnath08 wants to merge 2 commits intoschibsted:masterfrom
Conversation
Adds a built-in `filter(array, predicate)` macro that returns only the elements of an array for which the predicate expression is truthy. Must be a macro (not a function) so the predicate is re-evaluated with each element as the context node (`.`), matching the same pattern used by the existing `for` expression and `fallback` macro. Behaviour follows existing JSLT conventions: - null input → null (matches `for` expression) - non-array input → JsltException (matches `for` expression) - empty array → [] - falsy/null predicate result → element excluded Includes dedicated test files (filter-tests.json, filter-error-tests.json) registered in QueryTest and QueryErrorTest.
|
I guess the question is whether this is necessary, since for expressions already do this. For example, can be written The gain in brevity is very small. |
|
Yeah, The main thing for me is readability: There's also a discoverability angle: people coming from JS/Python will just search for That said, if the preference here is to keep built-ins minimal, I get it — happy to close if that's the direction. |
Summary
Adds a built-in
filter(array, predicate)macro that returns only theelements of an array for which the predicate expression is truthy.
Why a macro (not a function)?
The predicate must be re-evaluated with each element as the context
node (
.). A regular function receives arguments already evaluated toa single value, so the predicate would be lost. This is the same reason
foris a language construct andfallbackis a macro.Behaviour
filter(null, expr)nullfilter([], expr)[]filter(nonArray, expr)JsltExceptionExamples
Changes
core/src/main/java/com/schibsted/spt/data/jslt/impl/BuiltinFunctions.javaFiltermacro class + registered inmacrosmapcore/src/test/resources/filter-tests.jsoncore/src/test/resources/filter-error-tests.jsoncore/src/test/java/com/schibsted/spt/data/jslt/QueryTest.javafilter-tests.jsoncore/src/test/java/com/schibsted/spt/data/jslt/QueryErrorTest.javafilter-error-tests.jsonfunctions.mdfilter()alongsidefallbackImplementation Details
FilterextendsAbstractMacro(same base asfallback) with a fixedarity of 2. At runtime:
parameters[0]once to get the arraynullif the array is null; throwsJsltExceptionif not an arrayparameters[1]with that element as the context nodeNodeUtils.isTrue(result)— consistent with howforhandles itsifclauseNo grammar or parser changes were needed — macros are dispatched by name
via
ParseContext.getMacro()inParserImpl.chainable2Expr(), the samemechanism used by
fallback.Related
ideas/filter.md,ideas/for-filter.md