Skip to content

Instantly share code, notes, and snippets.

@furryablack
Created March 4, 2021 13:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save furryablack/9fe8790716fd4ece0fd880764247ff61 to your computer and use it in GitHub Desktop.
Save furryablack/9fe8790716fd4ece0fd880764247ff61 to your computer and use it in GitHub Desktop.
Vue composition api measurements
/*
* @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