Skip to content

Like sync.Once, but for running functions once on a dynamic set of keys.

License

Notifications You must be signed in to change notification settings

spartan0x117/onceper

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

OncePer

A simple utility to run a command once per unique comparable key. Note that it uses a mutex and a map so it will not be as performant as a sync.Once.

This is intended to be used when you have a dynamic list of keys for which you want to run a function only once, each.

Usage

Do

Do runs the passed function once per unique key.

package main

import (
    "fmt"

    "github.com/spartan0x117/onceper"
)

func main() {
    o := onceper.New[string]()

    // Run a function once per unique key
    o.Do("key", func() {
        fmt.Println("Hello World!")
    })
    // Any subsequent calls to Do with the same key will not run the function, even
    // if the function is different
    o.Do("key", func() {
        fmt.Println("Goodbye World!")
    })

    // A different key will run the function again
    o.Do("key2", func() {
        fmt.Println("foo bar baz")
    })
}

Output:

Hello World!
foo bar baz

DoWith

DoWith runs the passed function once per unique key, passing the key to the function.

package main

import (
    "fmt"

    "github.com/spartan0x117/onceper"
)

func main() {
    o := onceper.New[string]()
    f := func(s string) {
        fmt.Printf("Hello %s!\n", s)
    }

    // Run a function once per unique key, passing the key to the function
    o.DoWith("world", f)
    // Any subsequent calls with the same key will not run
    o.DoWith("world", f)

    // A different key will run the function again
    o.DoWith("go", f)
}

Output:

Hello world!
Hello go!

About

Like sync.Once, but for running functions once on a dynamic set of keys.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages