-
Notifications
You must be signed in to change notification settings - Fork 1
/
fill.go
50 lines (39 loc) · 1.26 KB
/
fill.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package array
import (
"reflect"
"github.com/warriors-vn/go-dash/constants"
)
// Fill elements of an array (Slice) with a specified value within the specified range.
// The function accepts an array (Slice), a value to Fill with, and optional start and end indices.
// It returns the modified array with filled values.
// If the input is not a Slice or if the start or end indices are out of bounds, the function returns an error.
func Fill(array, input interface{}, start, end int) (interface{}, error) {
arrValue, inputValue := reflect.ValueOf(array), reflect.ValueOf(input)
if arrValue.Kind() != reflect.Slice && arrValue.Kind() != reflect.Array {
return nil, constants.ErrNotSlice
}
if start >= end || arrValue.Len() == 0 {
return array, nil
}
if start < 0 {
start = 0
}
if end < 0 {
end = 1
}
if end > arrValue.Len() {
end = arrValue.Len()
}
kind, result := arrValue.Index(0).Kind(), reflect.MakeSlice(arrValue.Type(), 0, 0)
for i := 0; i < arrValue.Len(); i++ {
if kind != inputValue.Kind() && kind != reflect.Interface {
return nil, constants.ErrIncompatible
}
if start <= i && i < end {
result = reflect.Append(result, inputValue)
} else {
result = reflect.Append(result, arrValue.Index(i))
}
}
return result.Interface(), nil
}