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(useMin): new function #1934

Merged
merged 1 commit 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
25 changes: 25 additions & 0 deletions packages/math/useMin/index.md
@@ -0,0 +1,25 @@
---
category: '@Math'
---

# useMin

Reactive `Math.min`.

## Usage

```ts
import { useMin } from '@vueuse/math'

const array = ref([1, 2, 3, 4])
const sum = useMin(array) // Ref<1>
```

```ts
import { useMin } from '@vueuse/math'

const a = ref(1)
const b = ref(3)

const sum = useMin(a, b, 2) // Ref<1>
```
53 changes: 53 additions & 0 deletions packages/math/useMin/index.test.ts
@@ -0,0 +1,53 @@
import { ref } from 'vue-demi'
import { useMin } from '.'

describe('useMin', () => {
it('should be defined', () => {
expect(useMin).toBeDefined()
})

it('should accept numbers', () => {
const v = useMin(50, 100)
expect(v.value).toBe(50)
})

it('should accept refs', () => {
const value1 = ref(10)
const value2 = ref(100)
const value3 = ref(1000)

const v = useMin(value1, value2, value3)
expect(v.value).toBe(10)

value1.value = 8
expect(v.value).toBe(8)

value2.value = 7
expect(v.value).toBe(7)

value3.value = 6
expect(v.value).toBe(6)
})

it('should accept numbers and refs', () => {
const value1 = 10
const value2 = ref(100)

const v = useMin(50, value1, value2)

expect(v.value).toBe(10)

value2.value = 0
expect(v.value).toBe(0)
})

it('should accept single arg', () => {
const v = useMin(50)
expect(v.value).toBe(50)
})

it('should accept zero arg', () => {
const v = useMin()
expect(v.value).toBe(Infinity)
})
})
21 changes: 21 additions & 0 deletions packages/math/useMin/index.ts
@@ -0,0 +1,21 @@
import type { ComputedRef } from 'vue-demi'
import { computed } from 'vue-demi'
import type { MaybeComputedRef } from '@vueuse/shared'
import type { MaybeComputedRefArgs } from '../utils'
import { resolveUnrefArgsFlat } from '../utils'

export function useMin(array: MaybeComputedRef<MaybeComputedRef<number>[]>): ComputedRef<number>
export function useMin(...args: MaybeComputedRef<number>[]): ComputedRef<number>

/**
* Reactive `Math.min`.
*
* @see https://vueuse.org/useMin
* @param values
*/
export function useMin(...args: MaybeComputedRefArgs<number>) {
return computed<number>(() => {
const array = resolveUnrefArgsFlat(args)
return Math.min(...array)
})
}