Skip to content

Commit

Permalink
fix: add a max option to increment/decrement
Browse files Browse the repository at this point in the history
  • Loading branch information
Arcath committed Mar 21, 2023
1 parent 853a510 commit 2b36921
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 16 deletions.
6 changes: 4 additions & 2 deletions src/functions/increment.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,18 @@ describe('Increment', () => {
expect(counter()).toBe(1)
expect(counter()).toBe(2)

const counterTwo = increment({initial: 10, increment: 5})
const counterTwo = increment({initial: 10, increment: 5, max: 20})

expect(counterTwo()).toBe(10)
expect(counterTwo()).toBe(15)
expect(counterTwo()).toBe(20)
expect(counterTwo()).toBe(20)

const counterThree = decrement({initial: 10})
const counterThree = decrement({initial: 10, max: 8})

expect(counterThree()).toBe(10)
expect(counterThree()).toBe(9)
expect(counterThree()).toBe(8)
expect(counterThree()).toBe(8)
})
})
48 changes: 34 additions & 14 deletions src/functions/increment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ export interface IncrementOptions {
initial: number
/** Value to increase counter by on each call, defaults to `1`. */
increment: number
/** Maximum value to increment to. */
max: number
}

/**
Expand All @@ -23,37 +25,55 @@ export type IncrementFunction = () => number
export const increment = (
options?: Partial<IncrementOptions>
): IncrementFunction => {
const {initial, increment: incrementBy} = defaults<IncrementOptions>(
options,
{
increment: 1,
initial: 0
}
)
const {
initial,
increment: incrementBy,
max
} = defaults<IncrementOptions>(options, {
increment: 1,
initial: 0,
max: 0
})

let counter = initial - incrementBy

return () => {
if (max !== 0 && counter >= max) {
return counter
}

counter += incrementBy

return counter
}
}

/**
* Returns a function that when called returns a number that decrements by the given ammount each time.
*
* @param IncrementOptions
* @returns `IncrementFunction`
*/
export const decrement = (
options: Partial<IncrementOptions>
): IncrementFunction => {
const {initial, increment: incrementBy} = defaults<IncrementOptions>(
options,
{
increment: 1,
initial: 0
}
)
const {
initial,
increment: incrementBy,
max
} = defaults<IncrementOptions>(options, {
increment: 1,
initial: 0,
max: 0
})

let counter = initial + incrementBy

return () => {
if (max !== 0 && counter <= max) {
return counter
}

counter -= incrementBy

return counter
Expand Down

0 comments on commit 2b36921

Please sign in to comment.