Skip to content

Commit

Permalink
feat(useMath): new function (#1935)
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Jul 17, 2022
1 parent f3262a1 commit aa3fd69
Show file tree
Hide file tree
Showing 4 changed files with 70 additions and 0 deletions.
23 changes: 23 additions & 0 deletions 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
```
29 changes: 29 additions & 0 deletions 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)
})
})
16 changes: 16 additions & 0 deletions 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<K extends keyof Math>(
key: K,
...args: ArgumentsType<Reactified<Math[K], true>>
): ReturnType<Reactified<Math[K], true>> {
return reactify(Math[key] as any)(...args) as any
}
2 changes: 2 additions & 0 deletions packages/shared/utils/types.ts
Expand Up @@ -62,6 +62,8 @@ export type ShallowUnwrapRef<T> = T extends Ref<infer P> ? P : T

export type Awaitable<T> = Promise<T> | T

export type ArgumentsType<T> = T extends (...args: infer U) => any ? U : never

export interface Pausable {
/**
* A ref indicate whether a pusable instance is active
Expand Down

0 comments on commit aa3fd69

Please sign in to comment.