...

Source file src/golang.conradwood.net/go-easyops/utils/array_comparer.go

Documentation: golang.conradwood.net/go-easyops/utils

     1  package utils
     2  
     3  import (
     4  	"reflect"
     5  )
     6  
     7  // compare two arrays. find Missing elements in one or the other
     8  type ArrayComparer struct {
     9  	elements_in_array_1_but_not_2 []int
    10  	elements_in_array_2_but_not_1 []int
    11  }
    12  
    13  /*
    14  Compare an array. It uses a custom "compare" function which must return true if two elements are equal.
    15  i refers to array1[i] and j refers to array2[j]
    16  TODO: check if we can use reflect.ValueOf(array1).Index(i) to remove the need for external comp function
    17  */
    18  func CompareArray(array1, array2 interface{}, comp func(i, j int) bool) *ArrayComparer {
    19  	res := &ArrayComparer{}
    20  	l1 := reflect.ValueOf(array1).Len()
    21  	l2 := reflect.ValueOf(array2).Len()
    22  	// check for elements in array1 that are not in array2
    23  	for i := 0; i < l1; i++ {
    24  		// check if element 'i' from 'array1' is in 'array2'
    25  		found := false
    26  		for j := 0; j < l2; j++ {
    27  			if comp(i, j) {
    28  				found = true
    29  				break
    30  			}
    31  		}
    32  		if !found {
    33  			res.elements_in_array_1_but_not_2 = append(res.elements_in_array_1_but_not_2, i)
    34  		}
    35  	}
    36  
    37  	// check for elements in array2 that are not in array1
    38  	for j := 0; j < l2; j++ {
    39  		// check if element 'j' from 'array2' is in 'array1'
    40  		found := false
    41  		for i := 0; i < l1; i++ {
    42  			if comp(i, j) {
    43  				found = true
    44  				break
    45  			}
    46  		}
    47  		if !found {
    48  			res.elements_in_array_2_but_not_1 = append(res.elements_in_array_2_but_not_1, j)
    49  		}
    50  	}
    51  
    52  	return res
    53  }
    54  
    55  // returns true if both arrays contain the same elements (disregarding the order they are in)
    56  func (ac *ArrayComparer) EqualElements() bool {
    57  	if len(ac.elements_in_array_1_but_not_2) == 0 && len(ac.elements_in_array_2_but_not_1) == 0 {
    58  		return true
    59  	}
    60  	return false
    61  }
    62  
    63  // returns indices of elements that are in array 1 but not array 2
    64  func (ac *ArrayComparer) ElementsIn1ButNot2() []int {
    65  	return ac.elements_in_array_1_but_not_2
    66  }
    67  
    68  // returns indices of elements that are in array 2 but not array 1
    69  func (ac *ArrayComparer) ElementsIn2ButNot1() []int {
    70  	return ac.elements_in_array_2_but_not_1
    71  }
    72  

View as plain text