gitlab.com/evatix-go/core@v1.3.55/coredata/stringslice/SafeIndexRanges.go (about)

     1  package stringslice
     2  
     3  import "gitlab.com/evatix-go/core/constants"
     4  
     5  // SafeIndexRanges get safe index range values
     6  // If index range is out of range or not found then empty string will be added to response
     7  //
     8  // Reference Example :
     9  // https://play.golang.org/p/GifVBDSqTJ2
    10  func SafeIndexRanges(
    11  	slice []string,
    12  	startIndexIncluding, endIndexIncluding int,
    13  ) []string {
    14  	lastIndex := len(slice) - 1
    15  	requestLength := endIndexIncluding - startIndexIncluding + 1 // +1 for endingIndex or same one if zero
    16  
    17  	if requestLength < 0 {
    18  		return []string{}
    19  	}
    20  
    21  	responseSlice := MakeLen(requestLength)
    22  	if lastIndex < constants.Zero || requestLength <= 0 {
    23  		return responseSlice
    24  	}
    25  
    26  	index := -1
    27  	for i := startIndexIncluding; i <= endIndexIncluding; i++ {
    28  		index++
    29  
    30  		if i > lastIndex || i < 0 {
    31  			continue
    32  		}
    33  
    34  		responseSlice[index] = slice[i]
    35  	}
    36  
    37  	return responseSlice
    38  }