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(useSum): new function #1837

Merged
merged 1 commit into from Jul 12, 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
1 change: 1 addition & 0 deletions packages/math/index.ts
Expand Up @@ -8,3 +8,4 @@ export * from './useClamp'
export * from './useFloor'
export * from './useProjection'
export * from './useRound'
export * from './useSum'
16 changes: 16 additions & 0 deletions 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)
```
15 changes: 15 additions & 0 deletions 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)
})
})
18 changes: 18 additions & 0 deletions 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<Array<MaybeComputedRef<number>>>): ComputedRef<number> {
return computed(
() => resolveUnref(nums).reduce(
(prev: number, curr: MaybeComputedRef<number>) => prev + resolveUnref(curr), 0,
),
)
}