All files / builtins/mock-observations/helpers rand-int-generator.ts

100% Statements 29/29
100% Branches 10/10
100% Functions 6/6
100% Lines 26/26

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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 695x     5x       5x     5x   5x       6x       6x 6x 1x     5x     6x 5x 1x     4x 1x     3x 1x     2x     6x 5x   5x           2x     5x   5x     5x     2x        
import {ERRORS} from '@grnsft/if-core/utils';
import {RandIntGeneratorParams, ConfigParams} from '@grnsft/if-core/types';
 
import {STRINGS} from '../../../config';
 
import {Generator} from '../interfaces';
 
const {GlobalConfigError} = ERRORS;
 
const {MISSING_GLOBAL_CONFIG, MISSING_MIN_MAX, INVALID_MIN_MAX, INVALID_NAME} =
  STRINGS;
 
export const RandIntGenerator = (
  name: string,
  config: ConfigParams
): Generator => {
  const next = () => ({
    [validatedName]: generateRandInt(getFieldToPopulate()),
  });
 
  const validateName = (name: string | null): string => {
    if (!name || name.trim() === '') {
      throw new GlobalConfigError(INVALID_NAME);
    }
 
    return name;
  };
 
  const validateConfig = (config: ConfigParams): {min: number; max: number} => {
    if (!config || Object.keys(config).length === 0) {
      throw new GlobalConfigError(MISSING_GLOBAL_CONFIG);
    }
 
    if (!config.min || !config.max) {
      throw new GlobalConfigError(MISSING_MIN_MAX);
    }
 
    if (config.min >= config.max) {
      throw new GlobalConfigError(INVALID_MIN_MAX(validatedName));
    }
 
    return {min: config.min, max: config.max};
  };
 
  const validatedName = validateName(name);
  const validatedConfig = validateConfig(config);
 
  const getFieldToPopulate = () => ({
    name: validatedName,
    min: validatedConfig.min,
    max: validatedConfig.max,
  });
 
  const generateRandInt = (
    randIntGenerator: RandIntGeneratorParams
  ): number => {
    const randomNumber = Math.random();
    const scaledNumber =
      randomNumber * (randIntGenerator.max - randIntGenerator.min) +
      randIntGenerator.min;
 
    return Math.trunc(scaledNumber);
  };
 
  return {
    next,
  };
};