Skip to content

Commit

Permalink
feat(useAverage): support rest usage
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Jul 12, 2022
1 parent bf05983 commit 8afa60e
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 5 deletions.
11 changes: 10 additions & 1 deletion packages/math/useAverage/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,14 @@ Get the average of an array reactively.
import { useAverage } from '@vueuse/math'

const list = ref([1, 2, 3])
const averageValue = useAverage(list)
const averageValue = useAverage(list) // Ref<2>
```

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

const a = ref(1)
const b = ref(3)

const averageValue = useAverage(a, b) // Ref<2>
```
11 changes: 11 additions & 0 deletions packages/math/useAverage/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,15 @@ describe('useAverage', () => {
last.value = 10
expect(v.value).toBe(4)
})

it('should work with rest', () => {
const a = ref(1)
const b = ref(2)
const sum = useAverage(a, () => b.value, 3)
expect(sum.value).toBe(2)
b.value = 11
expect(sum.value).toBe(5)
a.value = 10
expect(sum.value).toBe(8)
})
})
15 changes: 12 additions & 3 deletions packages/math/useAverage/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,23 @@ import { computed } from 'vue-demi'
import { resolveUnref } from '@vueuse/shared'
import type { MaybeComputedRef } from '@vueuse/shared'

export function useAverage(array: MaybeComputedRef<MaybeComputedRef<number>[]>): ComputedRef<number>
export function useAverage(...args: MaybeComputedRef<number>[]): ComputedRef<number>

/**
* Get the average of an array reactively
*
* @see https://vueuse.org/useAverage
*/
export function useAverage(array: MaybeComputedRef<MaybeComputedRef<number>[]>): ComputedRef<number> {
export function useAverage(...args: any[]): ComputedRef<number> {
return computed(() => {
const arr = resolveUnref(array)
return arr.reduce<number>((sum, v) => sum += resolveUnref(v), 0) / arr.length
const array = args
.flatMap<number>((i) => {
const v = resolveUnref(i)
if (Array.isArray(v))
return v.map(i => resolveUnref(i))
return [v]
})
return array.reduce<number>((sum, v) => sum += v, 0) / array.length
})
}
11 changes: 10 additions & 1 deletion packages/math/useSum/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,14 @@ Get the sum of an array reactively
import { useSum } from '@vueuse/math'

const array = ref([1, 2, 3, 4])
const sum = useSum(array)
const sum = useSum(array) // Ref<10>
```

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

const a = ref(1)
const b = ref(3)

const sum = useSum(a, b, 2) // Ref<6>
```

0 comments on commit 8afa60e

Please sign in to comment.