diff --git a/src/readonly/index.ts b/src/readonly/index.ts index 99884b21..3bf45372 100644 --- a/src/readonly/index.ts +++ b/src/readonly/index.ts @@ -4,6 +4,10 @@ export function readonly(source: Store): Store; export function readonly(source: Event): Event; export function readonly(source: Store | Event) { + if (!is.targetable(source)) { + return source; + } + if (is.store(source)) { return source.map((value) => value, { skipVoid: false }); } diff --git a/src/readonly/readme.md b/src/readonly/readme.md index 54de2e1f..b2f775ee 100644 --- a/src/readonly/readme.md +++ b/src/readonly/readme.md @@ -37,6 +37,8 @@ result = readonly(event); - `result: Store|Event` +Note: if passed argument is already derived, then argument returns as-is. + ### Example ```ts diff --git a/src/readonly/readonly.test.ts b/src/readonly/readonly.test.ts index 0a387b12..5e20cee4 100644 --- a/src/readonly/readonly.test.ts +++ b/src/readonly/readonly.test.ts @@ -14,3 +14,19 @@ it('should convert event to readonly event', () => { expect(is.targetable(result)).toBe(false); }); + +it('should return store as-is if it is already derived', () => { + const $store = createStore({}); + const $mapped = $store.map((state) => state); + const $result = readonly($mapped); + + expect($result).toBe($mapped); +}); + +it('should return event as-is if it is already derived', () => { + const event = createEvent(); + const mapped = event.map((value) => value); + const result = readonly(mapped); + + expect(result).toBe(mapped); +});