Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(useMath): new function #1935

Merged
merged 2 commits into from Jul 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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