All files / number/src counter.ts

100% Statements 7/7
100% Branches 3/3
100% Functions 6/6
100% Lines 6/6

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45                                                        7x 7x   7x     1x     2x     2x        
export type Counter = {
  get: () => number;
  set: (value: number) => void;
  inc: (delta?: number) => void;
  dec: (delta?: number) => void;
};
 
/**
 * Creates a {@link Counter} object with an optional `initialValue`, defaults to `0`.
 *
 * @example
 * Create a countdown
 * ```ts
 * const clickCountdown = counter(10);
 *
 * const handleClickEvent = () => {
 *   clickCountdown.dec();
 *
 *   if(isZero(clickCountdown.get())) {
 *     console.log("0");
 *     clickCountdown.set(5);
 *   }
 * };
 * ```
 *
 * @param initialValue - the initial value
 * @returns the Counter object
 */
export const counter = (initialValue = 0): Counter => {
  return {
    get() {
      return initialValue;
    },
    set(newValue) {
      initialValue = newValue;
    },
    inc(delta = 1) {
      initialValue = initialValue + delta;
    },
    dec(delta = 1) {
      initialValue = initialValue - delta;
    },
  };
};