All files / if-run/builtins/coefficient index.ts

100% Statements 22/22
100% Branches 5/5
100% Functions 6/6
100% Lines 21/21

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 685x   5x   5x   5x   5x   5x 5x   5x   8x 1x     7x   7x             7x           4x     4x 4x   4x             4x   4x                     5x         4x    
import {z, ZodType} from 'zod';
 
import {ERRORS, validateArithmeticExpression} from '@grnsft/if-core/utils';
import {ConfigParams, PluginParams} from '@grnsft/if-core/types';
import {PluginFactory} from '@grnsft/if-core/interfaces';
 
import {validate} from '../../../common/util/validations';
 
import {STRINGS} from '../../config';
 
const {ConfigError} = ERRORS;
const {MISSING_CONFIG} = STRINGS;
 
export const Coefficient = PluginFactory({
  configValidation: (config: ConfigParams) => {
    if (!config || !Object.keys(config)?.length) {
      throw new ConfigError(MISSING_CONFIG);
    }
 
    const configSchema = z.object({
      coefficient: z.preprocess(
        value => validateArithmeticExpression('coefficient', value, 'number'),
        z.number()
      ),
      'input-parameter': z.string().min(1),
      'output-parameter': z.string().min(1),
    });
 
    return validate<z.infer<typeof configSchema>>(
      configSchema as ZodType<any>,
      config
    );
  },
  inputValidation: (input: PluginParams, config: ConfigParams) => {
    const inputData = {
      'input-parameter': input[config['input-parameter']],
    };
    const validationSchema = z.record(z.string(), z.number());
    validate(validationSchema, inputData);
 
    return input;
  },
  implementation: async (inputs: PluginParams[], config: ConfigParams) => {
    const {
      'input-parameter': inputParameter,
      'output-parameter': outputParameter,
      coefficient,
    } = config;
 
    return inputs.map(input => ({
      ...input,
      [outputParameter]: calculateProduct(input, inputParameter, coefficient),
    }));
  },
  allowArithmeticExpressions: ['input-parameter', 'coefficient'],
});
 
/**
 * Calculates the product of the energy components.
 */
const calculateProduct = (
  input: PluginParams,
  inputParameter: string | number,
  coefficient: number
) =>
  (isNaN(Number(inputParameter)) ? input[inputParameter] : inputParameter) *
  coefficient;