Skip to content

Commit

Permalink
feat(useSum): new function
Browse files Browse the repository at this point in the history
  • Loading branch information
holazz committed Jul 10, 2022
1 parent c9a37ae commit b157b3f
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 0 deletions.
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,
),
)
}

0 comments on commit b157b3f

Please sign in to comment.