Created
March 4, 2021 13:37
-
-
Save furryablack/9fe8790716fd4ece0fd880764247ff61 to your computer and use it in GitHub Desktop.
Vue composition api measurements
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
/* | |
* @file: use-state.h.ts | |
*/ | |
import {Ref} from "vue"; | |
export type DispatchFn<T> = (nextValue: T) => void | |
export type ResetFn = () => void | |
export type State = object | number | string | boolean | null; | |
export type MapFn<T> = (currentValue: T, nextValue: T) => T | |
export type ResultCortege<T> = [Ref<T>, DispatchFn<T>, ResetFn] | |
/* | |
* @file: use-state.ts | |
*/ | |
import {ref, Ref} from "vue"; | |
import {DispatchFn, MapFn, ResetFn, State, ResultCortege} from "./use-state.h"; | |
export * from './use-state.h' | |
export const useState = <T extends State>(initValue: T, mapFn: MapFn<T> = (_, nextValue) => { | |
return nextValue; | |
}): ResultCortege<T> => { | |
const obs = ref<T>(initValue) as Ref<T>; | |
const dispatch: DispatchFn<T> = (nextValue: T): void => { | |
obs.value = mapFn(obs.value, nextValue) | |
}; | |
const reset: ResetFn = () => { | |
dispatch(initValue); | |
}; | |
return [obs, dispatch, reset]; | |
}; | |
/* | |
* @file: use-boolean.h.ts | |
*/ | |
import {DispatchFn, MapFn, ResetFn, State, ResultCortege} from "./use-state"; | |
export type DispatchBooleanFn = DispatchFn<boolean>; | |
export type ResetBooleanFn = ResetFn; | |
export type StateBoolean = Extract<State, boolean> | |
export type MapBooleanFn = MapFn<boolean>; | |
export type ResultBooleanCortege = ResultCortege<boolean> | |
/* | |
* @file: use-boolean.ts | |
* const [flag, toggle] = useBoolean(true|false) | |
*/ | |
import {useState} from "./use-state"; | |
import {MapBooleanFn, ResultBooleanCortege} from "./use-boolean.h"; | |
const mapFn: MapBooleanFn = (value: boolean) => !value; | |
export * from "./use-boolean.h"; | |
export const useBoolean = (initValue: boolean): ResultBooleanCortege => useState<boolean>(initValue, mapFn); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment