expr-lang / expr

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

Slices and last element of an array #246

Closed christophkreutzer closed 2 years ago

christophkreutzer commented 2 years ago

According to https://github.com/antonmedv/expr/blob/master/docs/Language-Definition.md#slices it is possible to slice arrays with various options. However I don't see an option to retrieve the last element of an array.

I tried array[:-1] but that doesn't seem to work. Is this case not supported or is the syntax different?

Use Case: I'm using Argo Workflows with Bitbucket webhooks, and would like to extract the last commit hash of the changes array.

antonmedv commented 2 years ago

I’m not sure. Let’s check code.

xio812 commented 2 years ago

This sounds like a use case for the patch method, doesn't it?

antonmedv commented 2 years ago

Expr uses https://pkg.go.dev/reflect#Value.Index So this is not possible to do yet. But yes, Patch can help, or we can add it to the code.

christophkreutzer commented 2 years ago

Thanks for your help! I wasn't sure where to look how it's implemented, as I'm not that fluent in Go.

But it's no issue at all - I just didn't realize it could easily be expressed with len() (not sure how I could miss that), as written in the docs linked by @roqenrox:

payload.changes[len(payload.changes)-1].toHash