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

100% Statements 23/23
100% Branches 5/5
100% Functions 5/5
100% Lines 23/23

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 69 70 71 72 73 74 75 76 77 78 795x     5x 5x   5x   5x   5x 5x   5x   8x 1x     7x           7x           7x 7x     7x   7x                   5x   5x 5x           5x                       5x           5x   5x    
import {z, ZodType} from 'zod';
 
import {PluginParams, ConfigParams} from '@grnsft/if-core/types';
import {PluginFactory} from '@grnsft/if-core/interfaces';
import {ERRORS} from '@grnsft/if-core/utils';
 
import {validate} from '../../../common/util/validations';
 
import {STRINGS} from '../../config';
 
const {ConfigError} = ERRORS;
const {MISSING_CONFIG} = STRINGS;
 
export const Exponent = PluginFactory({
  configValidation: (config: ConfigParams) => {
    if (!config || !Object.keys(config)?.length) {
      throw new ConfigError(MISSING_CONFIG);
    }
 
    const configSchema = z.object({
      'input-parameter': z.string().min(1),
      exponent: z.number(),
      'output-parameter': z.string().min(1),
    });
 
    return validate<z.infer<typeof configSchema>>(
      configSchema as ZodType<any>,
      config
    );
  },
  inputValidation: (input: PluginParams, config: ConfigParams) => {
    const inputParameter = config['input-parameter'];
    const inputData = {
      [inputParameter]: input[inputParameter],
    };
    const validationSchema = z.record(z.string(), z.number());
 
    return validate<z.infer<typeof validationSchema>>(
      validationSchema,
      inputData
    );
  },
  implementation: async (inputs: PluginParams[], config: ConfigParams) => {
    const {
      'input-parameter': inputParameter,
      exponent,
      'output-parameter': outputParameter,
    } = config;
 
    return inputs.map(input => {
      const calculatedResult = calculateExponent(
        input,
        inputParameter,
        exponent
      );
 
      return {
        ...input,
        [outputParameter]: calculatedResult,
      };
    });
  },
  allowArithmeticExpressions: ['input-parameter', 'exponent'],
});
 
/**
 * Calculates the input param raised by the power of a given exponent.
 */
const calculateExponent = (
  input: PluginParams,
  inputParameter: string | number,
  exponent: number
) => {
  const base =
    typeof inputParameter === 'number' ? inputParameter : input[inputParameter];
 
  return Math.pow(base, exponent);
};