@@ -584,6 +584,70 @@ var Builtins = []*ast.Function{
584
584
return anyType , fmt .Errorf ("cannot get values from %s" , args [0 ])
585
585
},
586
586
},
587
+ {
588
+ Name : "toPairs" ,
589
+ Func : func (args ... any ) (any , error ) {
590
+ if len (args ) != 1 {
591
+ return nil , fmt .Errorf ("invalid number of arguments (expected 1, got %d)" , len (args ))
592
+ }
593
+ v := reflect .ValueOf (args [0 ])
594
+ if v .Kind () != reflect .Map {
595
+ return nil , fmt .Errorf ("cannot transform %s to pairs" , v .Kind ())
596
+ }
597
+ keys := v .MapKeys ()
598
+ out := make ([][2 ]any , len (keys ))
599
+ for i , key := range keys {
600
+ out [i ] = [2 ]any {key .Interface (), v .MapIndex (key ).Interface ()}
601
+ }
602
+ return out , nil
603
+ },
604
+ Validate : func (args []reflect.Type ) (reflect.Type , error ) {
605
+ if len (args ) != 1 {
606
+ return anyType , fmt .Errorf ("invalid number of arguments (expected 1, got %d)" , len (args ))
607
+ }
608
+ switch kind (args [0 ]) {
609
+ case reflect .Interface , reflect .Map :
610
+ return arrayType , nil
611
+ }
612
+ return anyType , fmt .Errorf ("cannot transform %s to pairs" , args [0 ])
613
+ },
614
+ },
615
+ {
616
+ Name : "fromPairs" ,
617
+ Func : func (args ... any ) (any , error ) {
618
+ if len (args ) != 1 {
619
+ return nil , fmt .Errorf ("invalid number of arguments (expected 1, got %d)" , len (args ))
620
+ }
621
+ v := reflect .ValueOf (args [0 ])
622
+ if v .Kind () != reflect .Slice && v .Kind () != reflect .Array {
623
+ return nil , fmt .Errorf ("cannot transform %s from pairs" , v )
624
+ }
625
+ out := reflect .MakeMap (mapType )
626
+ for i := 0 ; i < v .Len (); i ++ {
627
+ pair := deref (v .Index (i ))
628
+ if pair .Kind () != reflect .Array && pair .Kind () != reflect .Slice {
629
+ return nil , fmt .Errorf ("invalid pair %v" , pair )
630
+ }
631
+ if pair .Len () != 2 {
632
+ return nil , fmt .Errorf ("invalid pair length %v" , pair )
633
+ }
634
+ key := pair .Index (0 )
635
+ value := pair .Index (1 )
636
+ out .SetMapIndex (key , value )
637
+ }
638
+ return out .Interface (), nil
639
+ },
640
+ Validate : func (args []reflect.Type ) (reflect.Type , error ) {
641
+ if len (args ) != 1 {
642
+ return anyType , fmt .Errorf ("invalid number of arguments (expected 1, got %d)" , len (args ))
643
+ }
644
+ switch kind (args [0 ]) {
645
+ case reflect .Interface , reflect .Slice , reflect .Array :
646
+ return mapType , nil
647
+ }
648
+ return anyType , fmt .Errorf ("cannot transform %s from pairs" , args [0 ])
649
+ },
650
+ },
587
651
{
588
652
Name : "sort" ,
589
653
Func : func (args ... any ) (any , error ) {
0 commit comments