Skip to content

Commit

Permalink
feat(useMin): new function (#1934)
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Jul 17, 2022
1 parent 53f4a8a commit f3262a1
Show file tree
Hide file tree
Showing 3 changed files with 99 additions and 0 deletions.
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)
})
}

0 comments on commit f3262a1

Please sign in to comment.