-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreplace.go
80 lines (78 loc) · 1.69 KB
/
replace.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package golist
func validateIndex(index, listLen int) (int, error) {
if index >= listLen || index < -1 {
return index, ErrIndexOutOfRange
} else if index == -1 {
index = listLen - 1
return index, nil
} else {
return index, nil
}
}
// Replace : replaces an element in the lsit using the elements index. returns error if index do not exist.
func (arr *List) Replace(element interface{}, index int) error {
switch arr.list.(type) {
case []int:
list := arr.list.([]int)
item := element.(int)
index, err := validateIndex(index, len(list))
if err != nil {
return err
}
list[index] = item
arr.list = list
return nil
case []int32:
list := arr.list.([]int32)
item := element.(int32)
index, err := validateIndex(index, len(list))
if err != nil {
return err
}
list[index] = item
arr.list = list
return nil
case []int64:
list := arr.list.([]int64)
item := element.(int64)
index, err := validateIndex(index, len(list))
if err != nil {
return err
}
list[index] = item
arr.list = list
return nil
case []float32:
list := arr.list.([]float32)
item := element.(float32)
index, err := validateIndex(index, len(list))
if err != nil {
return err
}
list[index] = item
arr.list = list
return nil
case []float64:
list := arr.list.([]float64)
item := element.(float64)
index, err := validateIndex(index, len(list))
if err != nil {
return err
}
list[index] = item
arr.list = list
return nil
case []string:
list := arr.list.([]string)
item := element.(string)
index, err := validateIndex(index, len(list))
if err != nil {
return err
}
list[index] = item
arr.list = list
return nil
default:
return ErrTypeNotsupported
}
}