aboutsummaryrefslogtreecommitdiff
path: root/cursed
diff options
context:
space:
mode:
authorXe Iaso <me@xeiaso.net>2023-08-18 13:29:01 -0400
committerXe Iaso <me@xeiaso.net>2023-08-18 13:29:01 -0400
commit3a99ad5429b92a10394a29789bea2890611fdbdd (patch)
tree43bb732f49218aff75a8f728b5af425ad87f015d /cursed
parent9f07593862868e97f5b6f95809fb17f0248ce3e7 (diff)
downloadx-3a99ad5429b92a10394a29789bea2890611fdbdd.tar.xz
x-3a99ad5429b92a10394a29789bea2890611fdbdd.zip
cursed: new package for UseState
Signed-off-by: Xe Iaso <me@xeiaso.net>
Diffstat (limited to 'cursed')
-rw-r--r--cursed/doc.go12
-rw-r--r--cursed/useState.go31
-rw-r--r--cursed/useState_test.go16
3 files changed, 59 insertions, 0 deletions
diff --git a/cursed/doc.go b/cursed/doc.go
new file mode 100644
index 0000000..b613846
--- /dev/null
+++ b/cursed/doc.go
@@ -0,0 +1,12 @@
+// Package cursed contains code that should never be used by anyone.
+//
+// This place is a message... and part of a system of messages... pay attention to it!
+// Sending this message was important to us. We considered ourselves to be a powerful culture.
+// This place is not a place of honor... no highly esteemed deed is commemorated here... nothing valued is here.
+// What is here was dangerous and repulsive to us. This message is a warning about danger.
+// The danger is in a particular location... it increases towards a center... the center of danger is here... of a particular size and shape, and below us.
+// The danger is still present, in your time, as it was in ours.
+// The danger is to the body, and it can kill.
+// The form of the danger is an emanation of energy.
+// The danger is unleashed only if you substantially disturb this place physically. This place is best shunned and left uninhabited.
+package cursed
diff --git a/cursed/useState.go b/cursed/useState.go
new file mode 100644
index 0000000..f5dcf0b
--- /dev/null
+++ b/cursed/useState.go
@@ -0,0 +1,31 @@
+package cursed
+
+import "sync"
+
+// UseState is a copy of the useState monad in React/Preact.
+//
+// This is a thread-safe stateful container that allows you to set
+// and get a shared value.
+//
+// Consumers should take care to NOT mutate any values in the fetched
+// variable.
+func UseState[T any](initial T) (func() T, func(T)) {
+ var (
+ lock sync.Mutex
+ data T = initial
+
+ set = func(upda T) {
+ lock.Lock()
+ defer lock.Unlock()
+ data = upda
+ }
+
+ get = func() T {
+ lock.Lock()
+ defer lock.Unlock()
+ return data
+ }
+ )
+
+ return get, set
+}
diff --git a/cursed/useState_test.go b/cursed/useState_test.go
new file mode 100644
index 0000000..6278034
--- /dev/null
+++ b/cursed/useState_test.go
@@ -0,0 +1,16 @@
+package cursed
+
+import "testing"
+
+func TestUseState(t *testing.T) {
+ val, setVal := UseState[string]("hi")
+
+ if val() != "hi" {
+ t.Errorf("wanted %q but got %q", "hi", val())
+ }
+
+ setVal("goodbye")
+ if val() != "goodbye" {
+ t.Errorf("wanted %q but got %q", "goodbye", val())
+ }
+}