Skip to content

Commit

Permalink
feat: function to calculate increment
Browse files Browse the repository at this point in the history
  • Loading branch information
Arcath committed Mar 23, 2023
1 parent d6d2983 commit 5ba46cb
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 7 deletions.
20 changes: 20 additions & 0 deletions src/functions/increment.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
})
27 changes: 20 additions & 7 deletions src/functions/increment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -27,22 +27,29 @@ export const increment = (
): IncrementFunction => {
const {
initial,
increment: incrementBy,
increment: incremental,
max
} = defaults<IncrementOptions>(options, {
increment: 1,
initial: 0,
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
}
Expand All @@ -59,22 +66,28 @@ export const decrement = (
): IncrementFunction => {
const {
initial,
increment: incrementBy,
increment: incremental,
max
} = defaults<IncrementOptions>(options, {
increment: 1,
initial: 0,
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
}
Expand Down

0 comments on commit 5ba46cb

Please sign in to comment.