Skip to content

Instantly share code, notes, and snippets.

@didasy
Last active February 28, 2020 06:36
Show Gist options
  • Save didasy/ee93fa05c742df98cb72 to your computer and use it in GitHub Desktop.
Save didasy/ee93fa05c742df98cb72 to your computer and use it in GitHub Desktop.
Golang Slice Helper Functions
/*
A bunch of slice helper functions
All of these modify the original slice
*/
package main
import (
"fmt"
)
func main() {
arr := []int{1,2,3,4,5,6,7,8,9,0}
a, arr := pop(arr, 4)
fmt.Println("Popped : ", a, arr)
a, arr = shift(arr)
fmt.Println("Shifted : ", a, arr)
arr = unshift(arr, 10)
fmt.Println("Unshifted: ", arr)
arr = reverse(arr)
fmt.Println("Reversed : ", arr)
arr = maps(arr, func (r int) int {
return r * 2
})
fmt.Println("Mapped : ", arr)
a = reduce(arr, func (prev int, now int) int {
return prev + now
})
fmt.Println("Reduced : ", a)
}
func pop(arr []int, x int) (int, []int) {
n := arr[x]
return n, append(arr[:x], arr[x+1:]...)[:len(arr)-1]
}
func shift(arr []int) (int, []int) {
n := arr[0]
return n, copy(arr[1:])
}
func unshift(arr []int, x int) []int {
return append([]int{x}, arr...)
}
func reverse(arr []int) []int {
var narr []int
for i := len(arr) - 1; i >= 0; i-- {
narr = append(narr, arr[i])
}
return narr
}
func maps(arr []int, f func(int) int) []int {
for i, v := range arr {
arr[i] = f(v)
}
return arr
}
func reduce(arr []int, f func(int, int) int) int {
var r int
for _, v := range arr {
r = f(r, v)
}
return r
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment