Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ae542c6

Browse files
Mutter45antfu
andauthored
fix(useArrayReduce): initialValue can be a function (#4243)
Co-authored-by: Anthony Fu <[email protected]>
1 parent b46d2a0 commit ae542c6

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

packages/shared/useArrayReduce/index.test.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,4 +37,15 @@ describe('useArrayReduce', () => {
3737
list.push({ num: 3 })
3838
expect(sum.value).toBe(6)
3939
})
40+
it.skipIf(isVue2)('should work with initialValue being a function', () => {
41+
const list = reactive([{ num: 1 }, { num: 2 }])
42+
const sum = useArrayReduce(list, (prev, val) => {
43+
prev.push(val.num)
44+
return prev
45+
}, (() => []) as unknown as number[])
46+
expect(sum.value).toEqual([1, 2])
47+
48+
list.push({ num: 3 })
49+
expect(sum.value).toEqual([1, 2, 3])
50+
})
4051
})

packages/shared/useArrayReduce/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ export function useArrayReduce<T>(
5757
// Depending on the behavior of reduce, undefined is also a valid initialization value,
5858
// and this code will distinguish the behavior between them.
5959
return args.length
60-
? resolved.reduce(reduceCallback, toValue(args[0]))
60+
? resolved.reduce(reduceCallback, typeof args[0] === 'function' ? toValue(args[0]()) : toValue(args[0]))
6161
: resolved.reduce(reduceCallback)
6262
})
6363
}

0 commit comments

Comments
 (0)