...

Source file src/github.com/thoas/go-funk/zip.go

Documentation: github.com/thoas/go-funk

     1  package funk
     2  
     3  import (
     4  	"reflect"
     5  )
     6  
     7  // Tuple is the return type of Zip
     8  type Tuple struct {
     9  	Element1 interface{}
    10  	Element2 interface{}
    11  }
    12  
    13  // Zip returns a list of tuples, where the i-th tuple contains the i-th element
    14  // from each of the input iterables. The returned list is truncated in length
    15  // to the length of the shortest input iterable.
    16  func Zip(slice1 interface{}, slice2 interface{}) []Tuple {
    17  	if !IsCollection(slice1) || !IsCollection(slice2) {
    18  		panic("First parameter must be a collection")
    19  	}
    20  
    21  	var (
    22  		minLength int
    23  		inValue1  = reflect.ValueOf(slice1)
    24  		inValue2  = reflect.ValueOf(slice2)
    25  		result    = []Tuple{}
    26  		length1   = inValue1.Len()
    27  		length2   = inValue2.Len()
    28  	)
    29  
    30  	if length1 <= length2 {
    31  		minLength = length1
    32  	} else {
    33  		minLength = length2
    34  	}
    35  
    36  	for i := 0; i < minLength; i++ {
    37  		newTuple := Tuple{
    38  			Element1: inValue1.Index(i).Interface(),
    39  			Element2: inValue2.Index(i).Interface(),
    40  		}
    41  		result = append(result, newTuple)
    42  	}
    43  	return result
    44  }
    45  

View as plain text