From 2b369216148ef9441ad6b9f1c5b126ace4797167 Mon Sep 17 00:00:00 2001 From: Adam Laycock Date: Tue, 21 Mar 2023 15:26:42 +0000 Subject: [PATCH] fix: add a max option to increment/decrement --- src/functions/increment.spec.ts | 6 +++-- src/functions/increment.ts | 48 +++++++++++++++++++++++---------- 2 files changed, 38 insertions(+), 16 deletions(-) diff --git a/src/functions/increment.spec.ts b/src/functions/increment.spec.ts index 7153974..4453735 100644 --- a/src/functions/increment.spec.ts +++ b/src/functions/increment.spec.ts @@ -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) }) }) diff --git a/src/functions/increment.ts b/src/functions/increment.ts index e302c9c..31a3361 100644 --- a/src/functions/increment.ts +++ b/src/functions/increment.ts @@ -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 } /** @@ -23,37 +25,55 @@ export type IncrementFunction = () => number export const increment = ( options?: Partial ): IncrementFunction => { - const {initial, increment: incrementBy} = defaults( - options, - { - increment: 1, - initial: 0 - } - ) + const { + initial, + increment: incrementBy, + max + } = defaults(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 ): IncrementFunction => { - const {initial, increment: incrementBy} = defaults( - options, - { - increment: 1, - initial: 0 - } - ) + const { + initial, + increment: incrementBy, + max + } = defaults(options, { + increment: 1, + initial: 0, + max: 0 + }) let counter = initial + incrementBy return () => { + if (max !== 0 && counter <= max) { + return counter + } + counter -= incrementBy return counter