diff --git a/src/functions/increment.spec.ts b/src/functions/increment.spec.ts index 4453735..42b19e0 100644 --- a/src/functions/increment.spec.ts +++ b/src/functions/increment.spec.ts @@ -21,5 +21,25 @@ describe('Increment', () => { expect(counterThree()).toBe(9) expect(counterThree()).toBe(8) expect(counterThree()).toBe(8) + + const counterFour = increment({ + increment: (current, count) => { + return 10 - count + } + }) + + expect(counterFour()).toBe(0) + expect(counterFour()).toBe(9) + expect(counterFour()).toBe(17) + + const counterFive = decrement({ + increment: (current, count) => { + return 10 - count + } + }) + + expect(counterFive()).toBe(0) + expect(counterFive()).toBe(-9) + expect(counterFive()).toBe(-17) }) }) diff --git a/src/functions/increment.ts b/src/functions/increment.ts index 31a3361..54e558f 100644 --- a/src/functions/increment.ts +++ b/src/functions/increment.ts @@ -4,7 +4,7 @@ export interface IncrementOptions { /** Initial Value for the counter, defaults to `0` */ initial: number /** Value to increase counter by on each call, defaults to `1`. */ - increment: number + increment: number | ((current: number, count: number) => number) /** Maximum value to increment to. */ max: number } @@ -27,7 +27,7 @@ export const increment = ( ): IncrementFunction => { const { initial, - increment: incrementBy, + increment: incremental, max } = defaults(options, { increment: 1, @@ -35,14 +35,21 @@ export const increment = ( max: 0 }) - let counter = initial - incrementBy + let counter = + initial - + (typeof incremental === 'number' ? incremental : incremental(initial, 0)) + + let count = 0 return () => { if (max !== 0 && counter >= max) { return counter } - counter += incrementBy + counter += + typeof incremental === 'number' + ? incremental + : incremental(initial, count++) return counter } @@ -59,7 +66,7 @@ export const decrement = ( ): IncrementFunction => { const { initial, - increment: incrementBy, + increment: incremental, max } = defaults(options, { increment: 1, @@ -67,14 +74,20 @@ export const decrement = ( max: 0 }) - let counter = initial + incrementBy + let counter = + initial + + (typeof incremental === 'number' ? incremental : incremental(initial, 0)) + let count = 0 return () => { if (max !== 0 && counter <= max) { return counter } - counter -= incrementBy + counter -= + typeof incremental === 'number' + ? incremental + : incremental(initial, count++) return counter }