expr-lang / expr

Expression language and expression evaluation for Go
https://expr-lang.org
MIT License
5.85k stars 378 forks source link

Feature request:two builtin array functions #670

Open huziu235 opened 3 weeks ago

huziu235 commented 3 weeks ago

some(array,n,predicate) Return true immediately when match n item , otherwise return false filterN(array,n,predicate) Return first n matches immediately, or all matches if matches less than n.

largeArray|some(2,#>100)

largeArray|filterN(n,#>100)

antonmedv commented 3 weeks ago

Hey @huziu235

What about, instead of introducing new builtins , we can solve this on optimizer level. For example, Expr already supports those optimization:

Lets add new optimization for those cases:

// Return true immediately when match n item , otherwise return false
count(largeArray, # > 100) >= 2

We can add an optimization which will do an early exit from count in case 2 or more element are found.

And this optimization:

// Return first n matches immediately, or all matches if matches less than n.
filter(largeArray, # > 100) | take(n)

Let's also add an early exit from filter as soon as n elements are found.

antonmedv commented 3 weeks ago

Expr already has len(filter()) to count() optimizer, so even this case will work:

len(filter(largeArray, # > 100)) >= 2