summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/shapex.test.ts17
-rw-r--r--src/shapex.ts15
2 files changed, 31 insertions, 1 deletions
diff --git a/src/shapex.test.ts b/src/shapex.test.ts
index 0e7b08d..35207bb 100644
--- a/src/shapex.test.ts
+++ b/src/shapex.test.ts
@@ -1,7 +1,7 @@
import { assertArrayIncludes, assertEquals } from "@std/assert";
import { assertSpyCall, spy } from "@std/testing/mock";
import { describe, it } from "@std/testing/bdd";
-import ShapeX, { EventCallback } from "./shapex.ts";
+import ShapeX, { type EventCallback } from "./shapex.ts";
describe("subscribe", () => {
it("subscribes to an event", () => {
@@ -364,4 +364,19 @@ describe("utility methods", () => {
assertEquals($.subscriptionCount("event1"), 2);
assertEquals($.subscriptionCount("event2"), 1);
});
+
+ it("returns updated state", () => {
+ const $ = ShapeX({ counter: 1 });
+
+ $.subscribe(
+ "event1",
+ (state) => ({ state: { counter: state.counter + 1 } }),
+ );
+
+ $.dispatch("event1");
+
+ assertEquals($.state(), {
+ counter: 2,
+ });
+ });
});
diff --git a/src/shapex.ts b/src/shapex.ts
index 3d9fd21..fce55d4 100644
--- a/src/shapex.ts
+++ b/src/shapex.ts
@@ -68,6 +68,11 @@ export type ShapeXInstance<T> = {
* Dispatch an event.
*/
dispatch: (eventName: string, ...args: unknown[]) => void;
+
+ /**
+ * Get the current state.
+ */
+ state: () => T;
};
/**
@@ -272,6 +277,15 @@ export default function ShapeX<T extends object>(
return Array.from(_subscriptions.keys());
};
+ /**
+ * Returns the current state.
+ *
+ * @returns {T} The current state.
+ */
+ const state = (): T => {
+ return _state;
+ }
+
return {
subscribe,
subscribeOnce,
@@ -279,5 +293,6 @@ export default function ShapeX<T extends object>(
subscriptionCount,
subscriptions,
dispatch,
+ state,
};
}