seitu
Version:
32 lines (31 loc) • 851 B
JavaScript
import { createReadableSubscription, createSubscription } from "../subscription/index.mjs";
//#region src/core/store/index.ts
/**
* Creates a reactive store with `get()`, `set()`, and `subscribe()`.
*
* @example
* ```ts twoslash
* import { createStore } from 'seitu'
*
* const store = createStore({ count: 0 })
* store.set(prev => ({ ...prev, count: prev.count + 1 }))
* store.subscribe(state => console.log(state))
* store.get() // { count: 1 }
* ```
*/
function createStore(initial) {
let state = initial;
const { subscribe, notify } = createSubscription();
const get = () => state;
return {
...createReadableSubscription(get, subscribe, notify),
set: (value) => {
const next = typeof value === "function" ? value(state) : value;
if (next === state) return;
state = next;
notify();
}
};
}
//#endregion
export { createStore };