Skip to content

Commit

Permalink
feat(useDebounceFn): support passing params tothe returned function
Browse files Browse the repository at this point in the history
  • Loading branch information
lmhcoding committed Sep 26, 2020
1 parent fb5821d commit 17c97f0
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 7 deletions.
8 changes: 5 additions & 3 deletions src/useDebounceFn.ts
@@ -1,13 +1,15 @@
import { watch } from 'vue'
import { useDebounce } from './useDebounce'

export function useDebounceFn(fn: Function, delay = 200) {
export function useDebounceFn<T extends (...rest: any[]) => any>(fn: T, delay = 200) {
const debounceValue = useDebounce(0, delay)
let params: Parameters<T>

watch(debounceValue, () => {
fn()
fn(...params)
})
return () => {
return (...rest: Parameters<T>) => {
params = rest
debounceValue.value++
}
}
10 changes: 7 additions & 3 deletions tests/useDebounceFn.test.ts
@@ -1,11 +1,13 @@
import { nextTick } from 'vue'
import { useDebounceFn } from '../src/useDebounceFn'

let callback: Function | null
let callback: (...rest: any[]) => any

beforeEach(() => {
jest.useFakeTimers()
callback = jest.fn()
callback = jest.fn((s: string) => {
console.log(s)
})
})

afterEach(() => {
Expand Down Expand Up @@ -36,8 +38,10 @@ test('timer should be cleared when calling the function returned by useDebounceF

test('callback should be called when timeout', async () => {
const debounceFn = useDebounceFn(callback!)
debounceFn()
debounceFn('1')
debounceFn('2')
jest.advanceTimersByTime(200)
await nextTick()
expect(callback!).toHaveBeenCalledTimes(1)
expect(callback!).toHaveBeenCalledWith('2')
})
2 changes: 1 addition & 1 deletion tests/useInterval.test.ts
Expand Up @@ -55,7 +55,7 @@ test('interval will be start after invoking start', () => {
clear!()
expect(clearInterval).toHaveBeenCalledTimes(1)
expect(clearInterval).toHaveBeenCalledWith(expect.any(Number))
start()
start!()
expect(setInterval).toHaveBeenCalled()
expect(setInterval).toHaveBeenCalledWith(expect.any(Function), 500)
jest.advanceTimersByTime(500)
Expand Down

0 comments on commit 17c97f0

Please sign in to comment.