Skip to content

Instantly share code, notes, and snippets.

package main
import (
"flag"
"strings"
)
type arrayFlags []string
func (a *arrayFlags) String() string {
@gammazero
gammazero / merge.go
Created February 2, 2024 04:58
Merge K sorted lists
package main
import (
"container/heap"
)
type priorityQueue [][]int
func (pq priorityQueue) Len() int { return len(pq) }
@gammazero
gammazero / option.go
Last active December 20, 2022 20:52
Option template
package server
import (
"fmt"
"time"
)
const (
defaultWriteTimeout = 30 * time.Second
defaultReadTimeout = 30 * time.Second
@gammazero
gammazero / file_exists.go
Last active November 10, 2022 02:10
Check if files and directories exist
func fileExists(filename string) bool {
_, err := os.Stat(filename)
return !errors.Is(err, fs.ErrNotExist)
}
func dirExists(name string) (bool, error) {
fi, err := os.Stat(name)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return false, nil
@gammazero
gammazero / hash_bench_test.go
Created November 23, 2021 20:54
Benchmark different hashes
package main
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"hash"
"hash/fnv"
"testing"
@gammazero
gammazero / channel_notes.txt
Created November 2, 2021 16:09
Golang channel notes
Channel Behaviors
* A receive from a nil channel blocks forever
* A receive from a closed channel returns the zero value immediately
* A receive on an empty channel blocks
* A send to a nil channel blocks forever
* A send to a closed channel panics
* A send to a full (or unbuffered) channel blocks until reader has read data
// longestCommonPrefix returns the string in compares that has the longest common prefix with s
func longestCommonPrefix(s string, compares ...string) string {
var longestMatched int
var longestCmp string
maxLength := len(s)
for _, c := range compares {
cmpLen := len(c)
if cmpLen > maxLength {
cmpLen = maxLength
}
function ask_yes_no() {
local prompt="$1"
while true; do
read -p "$prompt [y/n]?" yn
case "$yn" in
[Yy]* ) return 0;;
[Nn]* ) return 1;;
* ) echo "Please answer y or n";;
esac
done
package main
import (
"path"
"syscall"
)
// isMountPoint returns true if the given directory is a mountpoint
func isMountPoint(fileName string) (bool, error) {
dir := path.Clean(fileName)
@gammazero
gammazero / wp_track_jobs.go
Last active October 29, 2020 21:11
Track workerpool job completion
package main
import (
"context"
"errors"
"fmt"
"time"
"github.com/gammazero/workerpool"
)