diff --git a/packages/math/index.ts b/packages/math/index.ts index 75f1918d7cc..0a8b0970300 100644 --- a/packages/math/index.ts +++ b/packages/math/index.ts @@ -8,3 +8,4 @@ export * from './useClamp' export * from './useFloor' export * from './useProjection' export * from './useRound' +export * from './useSum' diff --git a/packages/math/useSum/index.md b/packages/math/useSum/index.md new file mode 100644 index 00000000000..5177702a231 --- /dev/null +++ b/packages/math/useSum/index.md @@ -0,0 +1,16 @@ +--- +category: '@Math' +--- + +# useSum + +Get the sum of a set of numbers. + +## Usage + +```ts +import { useSum } from '@vueuse/math' + +const nums = ref([1, 2, 3, 4]) +const sum = useSum(nums) +``` diff --git a/packages/math/useSum/index.test.ts b/packages/math/useSum/index.test.ts new file mode 100644 index 00000000000..2b4ce9fc402 --- /dev/null +++ b/packages/math/useSum/index.test.ts @@ -0,0 +1,15 @@ +import { ref } from 'vue-demi' +import { useSum } from '.' + +describe('useSum', () => { + it('should be defined', () => { + expect(useSum).toBeDefined() + }) + it('should work', () => { + const nums = ref([1, 2, 3, 4]) + const sum = useSum(nums) + expect(sum.value).toBe(10) + nums.value = [-1, -2, 3, 4] + expect(sum.value).toBe(4) + }) +}) diff --git a/packages/math/useSum/index.ts b/packages/math/useSum/index.ts new file mode 100644 index 00000000000..e4aba4c8960 --- /dev/null +++ b/packages/math/useSum/index.ts @@ -0,0 +1,18 @@ +import type { ComputedRef } from 'vue-demi' +import { computed } from 'vue-demi' +import type { MaybeComputedRef } from '@vueuse/shared' +import { resolveUnref } from '@vueuse/shared' + +/** + * Get the sum of a set of numbers. + * + * @see https://vueuse.org/useSum + * @param nums + */ +export function useSum(nums: MaybeComputedRef>>): ComputedRef { + return computed( + () => resolveUnref(nums).reduce( + (prev: number, curr: MaybeComputedRef) => prev + resolveUnref(curr), 0, + ), + ) +}