-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: react-like state resolver to use it in stateful hooks;
- Loading branch information
Showing
2 changed files
with
44 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |