Skip to content

Commit 9fd02eb

Browse files
committed
feat: react-like state resolver to use it in stateful hooks;
1 parent 58ddea3 commit 9fd02eb

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

src/__tests__/resolveHookState.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import { resolveHookState } from '../util/resolveHookState';
2+
3+
describe('resolveHookState', () => {
4+
it('should defined', () => {
5+
expect(resolveHookState).toBeDefined();
6+
});
7+
8+
it(`should return value as is if it's not a function`, () => {
9+
expect(resolveHookState(1)).toBe(1);
10+
expect(resolveHookState('HI!')).toBe('HI!');
11+
expect(resolveHookState(undefined)).toBe(undefined);
12+
});
13+
14+
it('should call passed function', () => {
15+
const spy = jest.fn();
16+
resolveHookState(spy);
17+
expect(spy).toHaveBeenCalled();
18+
});
19+
20+
it('should pass 2nd parameter to function', () => {
21+
const spy = jest.fn();
22+
resolveHookState(spy, 123);
23+
expect(spy).toHaveBeenCalled();
24+
expect(spy.mock.calls[0][0]).toBe(123);
25+
});
26+
});

src/util/resolveHookState.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
export type StateSetter<S> = (prevState: S) => S;
2+
export type InitialStateSetter<S> = () => S;
3+
4+
export type InitialHookState<S> = S | InitialStateSetter<S>;
5+
export type HookState<S> = S | StateSetter<S>;
6+
export type ResolvableHookState<S> = S | StateSetter<S> | InitialStateSetter<S>;
7+
8+
export function resolveHookState<S>(newState: S | InitialStateSetter<S>): S;
9+
export function resolveHookState<S>(newState: Exclude<HookState<any>, StateSetter<any>>, currentState: S): S;
10+
// tslint:disable-next-line:unified-signatures
11+
export function resolveHookState<S>(newState: StateSetter<S>, currentState: S): S;
12+
export function resolveHookState<S>(newState: ResolvableHookState<S>, currentState?: S): S {
13+
if (typeof newState === 'function') {
14+
return (newState as Function)(currentState);
15+
}
16+
17+
return newState as S;
18+
}

0 commit comments

Comments
 (0)