// Some standard utility functions for Dyynaform consumers import { ValueTransformer } from './interfaces'; // Dropdown Modified Input - Starts With / Contains / Matches const standardModifiers = ['Starts with', 'Contains', 'Matches']; const standardTransformer: ValueTransformer = { inputFn: val => { let modifier = 'Starts with'; if (/^%.*?%$/.test(val)) { modifier = 'Contains' } else if (/^[^%].*?[^%]$/.test(val)) { modifier = 'Matches' } else if (/^%.*/.test(val)) { modifier = 'Starts with'; } const transformedVal = val.replace(/%/g, '').trim(); return { modifier: modifier, value: transformedVal }; }, outputFn: (mod, val) => { let transformedValue; switch(mod) { case 'Starts with': transformedValue = `%${val}`; break; case 'Contains': transformedValue = `%${val}%`; break; case 'Matches': default: transformedValue = val; break; } return transformedValue; } }; // Generate array from CSV string const toArrTag = (str: TemplateStringsArray): string[] => str[0].split(',').map(key => key.trim()); // Pad array const arrayPad = (length: number) => (arr: string[]): any[] => [...arr, ...Array(length - arr.length).fill('')]; // Utility function for casting an array to metadata (useful for components that render FormGroups) const arrayToMeta = array => array.map(val => ({ name: val, 'value' : val })); // Exclude 'fieldsToExclude' from obj, returning a new object // fieldsToExclude can be an array of field keys or a CSV of field keys const excludeFields = (obj: StringMap, fieldsToExclude: string | string[]) => { const ex = Array.isArray(fieldsToExclude) ? fieldsToExclude : fieldsToExclude.split(',').map(key => key.trim()); return Object.entries(obj).reduce( (res, [key, val]) => ex.includes(key) ? res : { ...res, [key]: val }, {} ); } export { standardModifiers, standardTransformer, toArrTag, arrayPad, arrayToMeta, excludeFields };