diff --git a/packages/math/useMath/index.md b/packages/math/useMath/index.md new file mode 100644 index 00000000000..dfc44e842e2 --- /dev/null +++ b/packages/math/useMath/index.md @@ -0,0 +1,23 @@ +--- +category: '@Math' +--- + +# useMath + +Reactive `Math` methods. + +## Usage + +```ts +import { useMath } from '@vueuse/math' + +const base = ref(2) +const exponent = ref(3) +const result = useMath('pow', base, exponent) // Ref<8> + +const num = ref(2) +const root = useMath('sqrt', num) // Ref<1.4142135623730951> + +num.value = 4 +console.log(root.value) // 2 +``` diff --git a/packages/math/useMath/index.test.ts b/packages/math/useMath/index.test.ts new file mode 100644 index 00000000000..766e9970e17 --- /dev/null +++ b/packages/math/useMath/index.test.ts @@ -0,0 +1,29 @@ +import { ref } from 'vue-demi' +import { useMath } from '.' + +describe('useMath', () => { + it('should be defined', () => { + expect(useMath).toBeDefined() + }) + + it('should accept numbers', () => { + const v = useMath('pow', 2, 3) + expect(v.value).toBe(8) + }) + + it('should accept refs', () => { + const base = ref(2) + const exponent = ref(3) + const result = useMath('pow', base, exponent) + + expect(result.value).toBe(8) + + const num = ref(4) + const root = useMath('sqrt', num) + + expect(root.value).toBe(2) + + num.value = 16 + expect(root.value).toBe(4) + }) +}) diff --git a/packages/math/useMath/index.ts b/packages/math/useMath/index.ts new file mode 100644 index 00000000000..ce79546b146 --- /dev/null +++ b/packages/math/useMath/index.ts @@ -0,0 +1,16 @@ +import type { ArgumentsType, Reactified } from '@vueuse/shared' +import { reactify } from '@vueuse/shared' + +export type UseMathKeys = keyof { [K in keyof Math as Math[K] extends (...args: any) => any ? K : never]: unknown } + +/** + * Reactive `Math` methods. + * + * @see https://vueuse.org/useMath + */ +export function useMath( + key: K, + ...args: ArgumentsType> +): ReturnType> { + return reactify(Math[key] as any)(...args) as any +} diff --git a/packages/shared/utils/types.ts b/packages/shared/utils/types.ts index 92dd3ecdade..daabeaf9fa2 100644 --- a/packages/shared/utils/types.ts +++ b/packages/shared/utils/types.ts @@ -62,6 +62,8 @@ export type ShallowUnwrapRef = T extends Ref ? P : T export type Awaitable = Promise | T +export type ArgumentsType = T extends (...args: infer U) => any ? U : never + export interface Pausable { /** * A ref indicate whether a pusable instance is active