Skip to content

Commit

Permalink
feat(useAverage): new function (#1826)
Browse files Browse the repository at this point in the history
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
colgin and antfu committed Jul 10, 2022
1 parent c9a37ae commit 9b0716c
Show file tree
Hide file tree
Showing 4 changed files with 88 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/math/index.ts
Expand Up @@ -3,6 +3,7 @@ export * from './createProjection'
export * from './logicAnd'
export * from './logicNot'
export * from './logicOr'
export * from './useAverage'
export * from './useCeil'
export * from './useClamp'
export * from './useFloor'
Expand Down
16 changes: 16 additions & 0 deletions packages/math/useAverage/index.md
@@ -0,0 +1,16 @@
---
category: '@Math'
---

# useAverage

Get the average of an array reactively.

## Usage

```ts
import { useAverage } from '@vueuse/math'

const list = ref([1, 2, 3])
const averageValue = useAverage(list)
```
55 changes: 55 additions & 0 deletions packages/math/useAverage/index.test.ts
@@ -0,0 +1,55 @@
import { ref } from 'vue-demi'
import { useAverage } from '.'

describe('useAverage', () => {
it('should be defined', () => {
expect(useAverage).toBeDefined()
})

it('should be the average', () => {
const arr = ref([1, 2, 3])

const v = useAverage(arr)

expect(v.value).toBe(2)

arr.value = [4, 5, 6]
expect(v.value).toBe(5)
})

it('should be the average when some are ref', () => {
const a = ref(2)
const arr = ref([1, a, 9])

const v = useAverage(arr)

expect(v.value).toBe(4)

a.value = 8
expect(v.value).toBe(6)
})

it('should be the average when some items are getter', () => {
const a = ref(1)
const arr = ref([1, () => a.value + 1, 9])

const v = useAverage(arr)

expect(v.value).toBe(4)

a.value = 7
expect(v.value).toBe(6)
})

it('should be the average when the array is a getter', () => {
const arr = ref([1, 2, 3])
const last = ref(0)

const v = useAverage(() => arr.value.concat(last.value))

expect(v.value).toBe(1.5)

last.value = 10
expect(v.value).toBe(4)
})
})
16 changes: 16 additions & 0 deletions packages/math/useAverage/index.ts
@@ -0,0 +1,16 @@
import type { ComputedRef } from 'vue-demi'
import { computed } from 'vue-demi'
import { resolveUnref } from '@vueuse/shared'
import type { MaybeComputedRef } from '@vueuse/shared'

/**
* Get the average of an array reactively
*
* @see https://vueuse.org/useAverage
*/
export function useAverage(array: MaybeComputedRef<MaybeComputedRef<number>[]>): ComputedRef<number> {
return computed(() => {
const arr = resolveUnref(array)
return arr.reduce<number>((sum, v) => sum += resolveUnref(v), 0) / arr.length
})
}

0 comments on commit 9b0716c

Please sign in to comment.