Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion src/readonly/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
import { Store, Event, is, combine } from 'effector';
import { Store, Event, is, createStore } from 'effector';

export function readonly<T extends unknown>(source: T): Store<T>;
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.unit(source)) {
if (typeof source === 'function' || source === undefined) {
return source;
}

return createStore(source).map((value) => value, { skipVoid: false });
}

if (!is.targetable(source)) {
return source;
}
Expand Down
29 changes: 29 additions & 0 deletions src/readonly/readonly.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,32 @@ it('should return event as-is if it is already derived', () => {

expect(result).toBe(mapped);
});

it('should convert non unit value to store', () => {
expect(is.store(readonly(1))).toBe(true);
expect(is.store(readonly('12'))).toBe(true);
expect(is.store(readonly(''))).toBe(true);
expect(is.store(readonly(true))).toBe(true);
expect(is.store(readonly(false))).toBe(true);
expect(is.store(readonly([]))).toBe(true);
expect(is.store(readonly({}))).toBe(true);
expect(is.store(readonly(null))).toBe(true);
expect(is.store(readonly(null))).toBe(true);

expect(is.targetable(readonly(1))).toBe(false);
expect(is.targetable(readonly('12'))).toBe(false);
expect(is.targetable(readonly(''))).toBe(false);
expect(is.targetable(readonly(true))).toBe(false);
expect(is.targetable(readonly(false))).toBe(false);
expect(is.targetable(readonly([]))).toBe(false);
expect(is.targetable(readonly({}))).toBe(false);
expect(is.targetable(readonly(null))).toBe(false);
expect(is.targetable(readonly(null))).toBe(false);
});

it('sould return value as-is if it is not unit and function or undefined', () => {
expect(is.store(readonly(() => {}))).toBe(false);
expect(is.store(readonly(undefined))).toBe(false);
expect(is.targetable(readonly(() => {}))).toBe(false);
expect(is.targetable(readonly(undefined))).toBe(false);
});
Loading