Skip to content

Commit

Permalink
feat: react-like state resolver to use it in stateful hooks;
Browse files Browse the repository at this point in the history
  • Loading branch information
xobotyi committed Oct 30, 2019
1 parent 58ddea3 commit 9fd02eb
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/__tests__/resolveHookState.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { resolveHookState } from '../util/resolveHookState';

describe('resolveHookState', () => {
it('should defined', () => {
expect(resolveHookState).toBeDefined();
});

it(`should return value as is if it's not a function`, () => {
expect(resolveHookState(1)).toBe(1);
expect(resolveHookState('HI!')).toBe('HI!');
expect(resolveHookState(undefined)).toBe(undefined);
});

it('should call passed function', () => {
const spy = jest.fn();
resolveHookState(spy);
expect(spy).toHaveBeenCalled();
});

it('should pass 2nd parameter to function', () => {
const spy = jest.fn();
resolveHookState(spy, 123);
expect(spy).toHaveBeenCalled();
expect(spy.mock.calls[0][0]).toBe(123);
});
});
18 changes: 18 additions & 0 deletions src/util/resolveHookState.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
export type StateSetter<S> = (prevState: S) => S;
export type InitialStateSetter<S> = () => S;

export type InitialHookState<S> = S | InitialStateSetter<S>;
export type HookState<S> = S | StateSetter<S>;
export type ResolvableHookState<S> = S | StateSetter<S> | InitialStateSetter<S>;

export function resolveHookState<S>(newState: S | InitialStateSetter<S>): S;
export function resolveHookState<S>(newState: Exclude<HookState<any>, StateSetter<any>>, currentState: S): S;
// tslint:disable-next-line:unified-signatures
export function resolveHookState<S>(newState: StateSetter<S>, currentState: S): S;
export function resolveHookState<S>(newState: ResolvableHookState<S>, currentState?: S): S {
if (typeof newState === 'function') {
return (newState as Function)(currentState);
}

return newState as S;
}

0 comments on commit 9fd02eb

Please sign in to comment.