Very Basic Recipes
Ternary
package golang
func Ternary[T any](condition bool, ifTrue T, ifFalse T) T {
if condition {
return ifTrue
}
return ifFalse
}
func Ternary[T any](condition bool, ifTrue T, ifFalse T) T {
if condition {
return ifTrue
}
return ifFalse
}
Convert String To Stream and Back
package golang
import (
"bytes"
"io"
"io/ioutil"
)
func StringToStream(s string) io.Reader {
return bytes.NewBuffer([]byte(s))
}
func StreamToString(r io.Reader) string {
if r == nil {
return ""
}
bts, e := ioutil.ReadAll(r)
if e != nil {
panic(e)
}
return string(bts)
}
import (
"bytes"
"io"
"io/ioutil"
)
func StringToStream(s string) io.Reader {
return bytes.NewBuffer([]byte(s))
}
func StreamToString(r io.Reader) string {
if r == nil {
return ""
}
bts, e := ioutil.ReadAll(r)
if e != nil {
panic(e)
}
return string(bts)
}
Reverse a String
This is a frequent coding interview challenge.
package golang
func Reverse(s string) string {
x := []byte(s)
for i := 0; i < len(x)/2; i++ {
x[i], x[len(x)-i-1] = x[len(x)-i-1], x[i]
}
return string(x)
}
func Reverse(s string) string {
x := []byte(s)
for i := 0; i < len(x)/2; i++ {
x[i], x[len(x)-i-1] = x[len(x)-i-1], x[i]
}
return string(x)
}