diff options
| author | Shulhan <ms@kilabit.info> | 2019-03-02 06:26:35 +0700 |
|---|---|---|
| committer | Shulhan <ms@kilabit.info> | 2019-03-02 06:26:35 +0700 |
| commit | 4d522fa86a8ff2c4468c7e1adff5665c405bb07c (patch) | |
| tree | 9e929a79d1bad3c4dbe9b4a5c63a8823cea081ba /lib/ints | |
| parent | 8a5dfcccd447a9e2693bace81525d6264abccc63 (diff) | |
| download | pakakeh.go-4d522fa86a8ff2c4468c7e1adff5665c405bb07c.tar.xz | |
ints: add function to remove value from slice
The Remove function remove value "v" from slice if its exist and return
new slice and true; otherwise, if not found, return unmodified slice and
false.
Diffstat (limited to 'lib/ints')
| -rw-r--r-- | lib/ints/ints.go | 14 | ||||
| -rw-r--r-- | lib/ints/ints_test.go | 30 |
2 files changed, 44 insertions, 0 deletions
diff --git a/lib/ints/ints.go b/lib/ints/ints.go index 09a5cbf1..73b915dd 100644 --- a/lib/ints/ints.go +++ b/lib/ints/ints.go @@ -233,6 +233,20 @@ func MinRange(d []int, l, r int) (v, i int) { } // +// Remove value "v" from slice if its exist and return new slice and true; +// otherwise, if not found, return unmodified slice and false. +// +func Remove(d []int, v int) ([]int, bool) { + for x := 0; x < len(d); x++ { + if d[x] == v { + d = append(d[:x], d[x+1:]...) + return d, true + } + } + return d, false +} + +// // SortByIndex will sort the slice `d` using sorted index `sortedIds`. // func SortByIndex(d *[]int, sortedIds []int) { diff --git a/lib/ints/ints_test.go b/lib/ints/ints_test.go index 58800bea..5e7111d4 100644 --- a/lib/ints/ints_test.go +++ b/lib/ints/ints_test.go @@ -397,3 +397,33 @@ func TestIndirectSort_SortByIndex(t *testing.T) { test.Assert(t, "", exp, got, true) } + +func TestRemove(t *testing.T) { + cases := []struct { + d []int + v int + exp []int + }{{ + d: []int{}, + v: 1, + exp: []int{}, + }, { + d: []int{1}, + v: 1, + exp: []int{}, + }, { + d: []int{1, 2, 3, 4}, + v: 5, + exp: []int{1, 2, 3, 4}, + }, { + d: []int{1, 2, 3, 4}, + v: 1, + exp: []int{2, 3, 4}, + }} + + for _, c := range cases { + got, _ := Remove(c.d, c.v) + + test.Assert(t, "Remove", c.exp, got, true) + } +} |
