# Go cheatsheet - Slice Utilities

## Slice

### Empty a slice
```go
a := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
a = a[:0]
// or
a = nil
```

### Prepend
```go
b := []int{2, 3, 4}
b = append([]int{1}, b...)
```

### Remove
```go
a = append(a[:i], a[i+1:]...)
```

### Insert at index
```go
s = append(s, 0)
copy(s[i+1:], s[i:])
s[i] = x
```

### Index/Find element

```go
func Index(vs []string, t string) int {
    for i, v := range vs {
        if v == t {
            return i
        }
    }
    return -1
}
```

### Include/Contain

```go
func Include(vs []string, t string) bool {
    return Index(vs, t) >= 0
}
```

### Any & All

```go
func Any(vs []string, f func(string) bool) bool {
    for _, v := range vs {
        if f(v) {
            return true
        }
    }
    return false
}

func All(vs []string, f func(string) bool) bool {
    for _, v := range vs {
        if !f(v) {
            return false
        }
    }
    return true
}
```

### Filter

```go
func Filter(vs []string, f func(string) bool) []string {
    vsf := make([]string, 0)
    for _, v := range vs {
        if f(v) {
            vsf = append(vsf, v)
        }
    }
    return vsf
}
```

### Map

```go
func Map(vs []string, f func(string) string) []string {
    vsm := make([]string, len(vs))
    for i, v := range vs {
        vsm[i] = f(v)
    }
    return vsm
}
```
