diff --git a/README.md b/README.md index 79961a4..eeba8c5 100644 --- a/README.md +++ b/README.md @@ -97,6 +97,11 @@ interface Signal { value: T; changed: () => void; edit: (editor: (value: T) => void) => void; + // Aliases + get: () => T; + r: () => T; + set: (value: T) => void; + w: (value: T) => void; } ``` diff --git a/src/index.ts b/src/index.ts index b85915a..4d49abb 100644 --- a/src/index.ts +++ b/src/index.ts @@ -29,8 +29,14 @@ export type Action = (dispose: Disposer) => T; export interface Signal { /** Read value. */ (): T; + /** Read value. */ + get: () => T; + r: () => T; /** Set value. */ (value: T): void; + /** Set value. */ + set: (value: T) => void; + w: (value: T) => void; /** Non-reactive reference to value. */ value: T; /** Manually triggers value change signal. */ @@ -264,10 +270,21 @@ export function signal(value: T): Signal { function getSet(): T; function getSet(value: T): void; function getSet(value?: T) { - return arguments.length ? write(value!) : read(); + return arguments.length ? getSet.w(value!) : getSet.r(); } getSet.value = value; + getSet.get = getSet.r = () => { + registerDependency(getSet); + return getSet.value; + }; + getSet.set = getSet.w = (value: T) => { + if (disallowWrites) throw new Error(`Writing to signals not allowed in this context.`); + if (value !== getSet.value) { + getSet.value = value; + getSet.changed(); + } + }; getSet.changed = () => { if (!effectQueue) bulkEffects(() => triggerObservers(getSet)); else triggerObservers(getSet); @@ -276,20 +293,7 @@ export function signal(value: T): Signal { editor(getSet.value); getSet.changed(); }; - getSet.toJSON = () => toJSON(read()); - - function read() { - registerDependency(getSet); - return getSet.value; - } - - function write(value: T) { - if (disallowWrites) throw new Error(`Writing to signals not allowed in this context.`); - if (value !== getSet.value) { - getSet.value = value; - getSet.changed(); - } - } + getSet.toJSON = () => toJSON(getSet.r()); return getSet; } diff --git a/test.ts b/test.ts index 13b7881..975cfc0 100644 --- a/test.ts +++ b/test.ts @@ -6,12 +6,34 @@ test(`calling a signal with no argument reads it`, (t) => { t.is(s(), 'foo'); }); +test(`signal.get reads the signal`, (t) => { + const s = signal('foo'); + t.is(s.get(), 'foo'); +}); + +test(`signal.r() is an alias of signal.get()`, (t) => { + const s = signal('foo'); + t.is(s.get, s.r); +}); + test(`calling a signal with one argument sets it`, (t) => { const s = signal('foo'); s('bar'); t.is(s(), 'bar'); }); +test(`signal.set(value) sets the signal`, (t) => { + const s = signal('foo'); + s.set('bar'); + t.is(s(), 'bar'); +}); + +test(`signal.w() is an alias of signal.set()`, (t) => { + const s = signal('foo'); + s.set('bar'); + t.is(s.set, s.w); +}); + test(`signal.value points to the current value`, (t) => { const obj = {}; const s = signal(obj);