github.com/hyperledger/burrow@v0.34.5-0.20220512172541-77f09336001d/util/slice/slice.go (about) 1 // Copyright Monax Industries Limited 2 // SPDX-License-Identifier: Apache-2.0 3 4 package slice 5 6 // Convenience function 7 func Slice(elements ...interface{}) []interface{} { 8 return elements 9 } 10 11 func EmptySlice() []interface{} { 12 return []interface{}{} 13 } 14 15 // Like append but on the interface{} type and always to a fresh backing array 16 // so can be used safely with slices over arrays you did not create. 17 func CopyAppend(slice []interface{}, elements ...interface{}) []interface{} { 18 sliceLength := len(slice) 19 newSlice := make([]interface{}, sliceLength+len(elements)) 20 copy(newSlice, slice) 21 copy(newSlice[sliceLength:], elements) 22 return newSlice 23 } 24 25 // Prepend elements to slice in the order they appear 26 func CopyPrepend(slice []interface{}, elements ...interface{}) []interface{} { 27 elementsLength := len(elements) 28 newSlice := make([]interface{}, len(slice)+elementsLength) 29 copy(newSlice, elements) 30 copy(newSlice[elementsLength:], slice) 31 return newSlice 32 } 33 34 // Concatenate slices into a single slice 35 func Concat(slices ...[]interface{}) []interface{} { 36 offset := 0 37 for _, slice := range slices { 38 offset += len(slice) 39 } 40 concat := make([]interface{}, offset) 41 offset = 0 42 for _, slice := range slices { 43 for i, e := range slice { 44 concat[offset+i] = e 45 } 46 offset += len(slice) 47 } 48 return concat 49 } 50 51 // Deletes n elements starting with the ith from a slice by splicing. 52 // Beware uses append so the underlying backing array will be modified! 53 func Delete(slice []interface{}, i int, n int) []interface{} { 54 return append(slice[:i], slice[i+n:]...) 55 } 56 57 // Flatten a slice by a list by splicing any elements of the list that are 58 // themselves lists into the slice elements to the list in place of slice itself 59 func Flatten(slice []interface{}) []interface{} { 60 return DeepFlatten(slice, 1) 61 } 62 63 // Recursively flattens a list by splicing any sub-lists into their parent until 64 // depth is reached. If a negative number is passed for depth then it continues 65 // until no elements of the returned list are lists 66 func DeepFlatten(slice []interface{}, depth int) []interface{} { 67 if depth == 0 { 68 return slice 69 } 70 returnSlice := []interface{}{} 71 72 for _, element := range slice { 73 if s, ok := element.([]interface{}); ok { 74 returnSlice = append(returnSlice, DeepFlatten(s, depth-1)...) 75 } else { 76 returnSlice = append(returnSlice, element) 77 } 78 79 } 80 81 return returnSlice 82 }