diff --git a/packages/math/useMin/index.md b/packages/math/useMin/index.md new file mode 100644 index 00000000000..17ff4763603 --- /dev/null +++ b/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> +``` diff --git a/packages/math/useMin/index.test.ts b/packages/math/useMin/index.test.ts new file mode 100644 index 00000000000..df81c9f9044 --- /dev/null +++ b/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) + }) +}) diff --git a/packages/math/useMin/index.ts b/packages/math/useMin/index.ts new file mode 100644 index 00000000000..89f1448c0d1 --- /dev/null +++ b/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[]>): ComputedRef +export function useMin(...args: MaybeComputedRef[]): ComputedRef + +/** + * Reactive `Math.min`. + * + * @see https://vueuse.org/useMin + * @param values + */ +export function useMin(...args: MaybeComputedRefArgs) { + return computed(() => { + const array = resolveUnrefArgsFlat(args) + return Math.min(...array) + }) +}