15
15
package cel
16
16
17
17
import (
18
+ "fmt"
18
19
"math"
19
20
"strconv"
20
21
"strings"
@@ -35,6 +36,7 @@ const (
35
36
optMapMacro = "optMap"
36
37
optFlatMapMacro = "optFlatMap"
37
38
hasValueFunc = "hasValue"
39
+ elideOptFunc = "elideOpt"
38
40
optionalNoneFunc = "optional.none"
39
41
optionalOfFunc = "optional.of"
40
42
optionalOfNonZeroValueFunc = "optional.ofNonZeroValue"
@@ -281,6 +283,14 @@ func (stdLibrary) ProgramOptions() []ProgramOption {
281
283
//
282
284
// This is syntactic sugar for msg.elements[msg.elements.size()-1].
283
285
286
+ // # ElideOpt
287
+ //
288
+ // Introduced in version: 2
289
+ //
290
+ // Returns a list of all the values that are not none in the input list of optional values.
291
+ //
292
+ // [optional.of(42), optional.none()].elideOpt() == [42]
293
+
284
294
func OptionalTypes (opts ... OptionalTypesOption ) EnvOption {
285
295
lib := & optionalLib {version : math .MaxUint32 }
286
296
for _ , opt := range opts {
@@ -324,6 +334,7 @@ func (lib *optionalLib) CompileOptions() []EnvOption {
324
334
optionalTypeV := OptionalType (paramTypeV )
325
335
listTypeV := ListType (paramTypeV )
326
336
mapTypeKV := MapType (paramTypeK , paramTypeV )
337
+ listOptionalTypeV := ListType (optionalTypeV )
327
338
328
339
opts := []EnvOption {
329
340
// Enable the optional syntax in the parser.
@@ -427,6 +438,25 @@ func (lib *optionalLib) CompileOptions() []EnvOption {
427
438
}),
428
439
),
429
440
))
441
+
442
+ opts = append (opts , Function (elideOptFunc ,
443
+ MemberOverload ("optional_elideOpt" , []* Type {listOptionalTypeV }, listTypeV ,
444
+ UnaryBinding (func (value ref.Val ) ref.Val {
445
+ list := value .(traits.Lister )
446
+ var elidedList []ref.Val
447
+ iter := list .Iterator ()
448
+ for iter .HasNext () == types .True {
449
+ val := iter .Next ()
450
+ opt , isOpt := val .(* types.Optional )
451
+ if ! isOpt {
452
+ return types .WrapErr (fmt .Errorf ("value %v is not optional" , val ))
453
+ }
454
+ if opt .HasValue () {
455
+ elidedList = append (elidedList , opt .GetValue ())
456
+ }
457
+ }
458
+ return types .DefaultTypeAdapter .NativeToValue (elidedList )
459
+ }))))
430
460
}
431
461
432
462
return opts
0 commit comments