Skip to content

Commit

Permalink
feat(readonly): implement readonly operator
Browse files Browse the repository at this point in the history
Improved implementation when argument is already derived.
  • Loading branch information
chshanovskiy committed Jan 18, 2024
1 parent 2df61ba commit a49a74c
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/readonly/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ export function readonly<T extends unknown>(source: Store<T>): Store<T>;
export function readonly<T extends unknown>(source: Event<T>): Event<T>;

export function readonly<T extends unknown>(source: Store<T> | Event<T>) {
if (!is.targetable(source)) {
return source;
}

if (is.store(source)) {
return source.map((value) => value, { skipVoid: false });
}
Expand Down
2 changes: 2 additions & 0 deletions src/readonly/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ result = readonly(event);

- `result: Store<T>|Event<T>`

Note: if passed argument is already derived, then argument returns as-is.

### Example

```ts
Expand Down
16 changes: 16 additions & 0 deletions src/readonly/readonly.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});

0 comments on commit a49a74c

Please sign in to comment.