Skip to content

Commit

Permalink
fix(useCounter): allow delta to be negative (#3650)
Browse files Browse the repository at this point in the history
Co-authored-by: Doctorwu <44631608+Doctor-wu@users.noreply.github.com>
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
3 people committed Feb 20, 2024
1 parent 318d082 commit cf29c4c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
14 changes: 13 additions & 1 deletion packages/shared/useCounter/index.test.ts
Expand Up @@ -18,10 +18,16 @@ describe('useCounter', () => {
inc(2)
expect(count.value).toBe(3)
expect(get()).toBe(3)
dec()
inc(-1)
expect(count.value).toBe(2)
expect(get()).toBe(2)
dec()
expect(count.value).toBe(1)
expect(get()).toBe(1)
dec(5)
expect(count.value).toBe(-4)
expect(get()).toBe(-4)
dec(-1)
expect(count.value).toBe(-3)
expect(get()).toBe(-3)
set(100)
Expand Down Expand Up @@ -87,6 +93,12 @@ describe('useCounter', () => {
inc(20)
expect(count.value).toBe(15)
expect(get()).toBe(15)
inc(-20)
expect(count.value).toBe(-2)
expect(get()).toBe(-2)
dec(-20)
expect(count.value).toBe(15)
expect(get()).toBe(15)
dec(2)
expect(count.value).toBe(13)
expect(get()).toBe(13)
Expand Down
4 changes: 2 additions & 2 deletions packages/shared/useCounter/index.ts
Expand Up @@ -24,8 +24,8 @@ export function useCounter(initialValue: MaybeRef<number> = 0, options: UseCount
min = Number.NEGATIVE_INFINITY,
} = options

const inc = (delta = 1) => count.value = Math.min(max, count.value + delta)
const dec = (delta = 1) => count.value = Math.max(min, count.value - delta)
const inc = (delta = 1) => count.value = Math.max(Math.min(max, count.value + delta), min)
const dec = (delta = 1) => count.value = Math.min(Math.max(min, count.value - delta), max)
const get = () => count.value
const set = (val: number) => (count.value = Math.max(min, Math.min(max, val)))
const reset = (val = _initialValue) => {
Expand Down

0 comments on commit cf29c4c

Please sign in to comment.