expr icon indicating copy to clipboard operation
expr copied to clipboard

Optional Chaining doesn't work for Out-of-range array indexes

Open 8BitJonny opened this issue 2 years ago • 6 comments

What

Using the Playground with the newest version 1.16 I expected Posts[10]?.Title to result in undefined whereas it throws

reflect: slice index out of range (3:6)
 | Posts[10]?.Title
 | .....^

Just like in JS [][1]?.a also works and yields null/undefined making things like [][1]?.a ?? 42 work where as Posts[10]?.Title ?? "default" does not work currently in with this library. Or is this expected/deliberate?

8BitJonny avatar Jan 29 '24 13:01 8BitJonny

In JS Posts[10] return undefined. This is why it is working in JS. In Expr Posts[10] will raise an error.

Not sure what is the best solution here.

antonmedv avatar Jan 29 '24 16:01 antonmedv

Expr for this purpose have a special builtin function get(array, index).

It will return nil instead of raised error:

get(Posts, 10)?.Title
let post = Posts | get(10);
post?.Title

antonmedv avatar Jan 29 '24 16:01 antonmedv

Another solution I'm looking into is adding an option to Expr to make all . access optional changing and to return nil insted of error on out of bound check.

antonmedv avatar Jan 29 '24 17:01 antonmedv

Expr for this purpose have a special builtin function get(array, index)

But this would get bulky very fast wouldn't it? I mean get(get(myDeepObject?.Prop, 10)?.NestedList, 1)?.value

Another solution I'm looking into is adding an option to Expr to make all . access optional changing and to return nil insted of error on out of bound check.

I would love that! I already thought of writing a Patcher that makes all MemberNodes Optional by default. This as an global option would be greatly appreciated and I also do see value here for other people as it makes the syntax a whole lot easier to write for non technical users and everyone can decide if they want to turn this option on or off

8BitJonny avatar Jan 30 '24 09:01 8BitJonny

I would love that! I already thought of writing a Patcher that makes all MemberNodes Optional by default. This as an global option would be greatly appreciated and I also do see value here for other people as it makes the syntax a whole lot easier to write for non technical users and everyone can decide if they want to turn this option on or off

I agree. Let's make an option to set all MemberNodes as optional.

Posts[10]

Make array access should return nil instead of rasing error by default. And have an option like expr.PanicOnOutOfBound().

antonmedv avatar Jan 30 '24 13:01 antonmedv

Love it

8BitJonny avatar Jan 30 '24 15:01 8BitJonny