/
index.ts
63 lines (58 loc) · 2.18 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import type { ComputedRef } from 'vue-demi'
import { computed } from 'vue-demi'
import type { MaybeComputedRef } from '../utils'
import { resolveUnref } from '../resolveUnref'
export type UseArrayReducer<PV, CV, R> = (previousValue: PV, currentValue: CV, currentIndex: number) => R
/**
* Reactive `Array.reduce`
*
* @see https://vueuse.org/useArrayReduce
* @param {Array} list - the array was called upon.
* @param reducer - a "reducer" function.
*
* @returns the value that results from running the "reducer" callback function to completion over the entire array.
*/
export function useArrayReduce<T>(
list: MaybeComputedRef<MaybeComputedRef<T>[]>,
reducer: UseArrayReducer<T, T, T>,
): ComputedRef<T>
/**
* Reactive `Array.reduce`
*
* @see https://vueuse.org/useArrayReduce
* @param {Array} list - the array was called upon.
* @param reducer - a "reducer" function.
* @param initialValue - a value to be initialized the first time when the callback is called.
*
* @returns the value that results from running the "reducer" callback function to completion over the entire array.
*/
export function useArrayReduce<T, U>(
list: MaybeComputedRef<MaybeComputedRef<T>[]>,
reducer: UseArrayReducer<U, T, U>,
initialValue: MaybeComputedRef<U>,
): ComputedRef<U>
/**
* Reactive `Array.reduce`
*
* @see https://vueuse.org/useArrayReduce
* @param {Array} list - the array was called upon.
* @param reducer - a "reducer" function.
* @param args
*
* @returns the value that results from running the "reducer" callback function to completion over the entire array.
*/
export function useArrayReduce<T>(
list: MaybeComputedRef<MaybeComputedRef<T>[]>,
reducer: ((...p: any[]) => any),
...args: any[]
): ComputedRef<T> {
const reduceCallback = (sum: any, value: any, index: number) => reducer(resolveUnref(sum), resolveUnref(value), index)
return computed(() => {
const resolved = resolveUnref(list)
// Depending on the behavior of reduce, undefined is also a valid initialization value,
// and this code will distinguish the behavior between them.
return args.length
? resolved.reduce(reduceCallback, resolveUnref(args[0]))
: resolved.reduce(reduceCallback)
})
}