utils.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Some standard utility functions for Dyynaform consumers
  2. import { ValueTransformer } from './interfaces';
  3. // Dropdown Modified Input - Starts With / Contains / Matches
  4. const standardModifiers = ['Starts with', 'Contains', 'Matches'];
  5. const standardTransformer: ValueTransformer = {
  6. inputFn: val => {
  7. let modifier = 'Starts with';
  8. if (/^%.*?%$/.test(val)) {
  9. modifier = 'Contains'
  10. } else if (/^[^%].*?[^%]$/.test(val)) {
  11. modifier = 'Matches'
  12. } else if (/^%.*/.test(val)) {
  13. modifier = 'Starts with';
  14. }
  15. const transformedVal = val.replace(/%/g, '').trim();
  16. return { modifier: modifier, value: transformedVal };
  17. },
  18. outputFn: (mod, val) => {
  19. let transformedValue;
  20. switch(mod) {
  21. case 'Starts with':
  22. transformedValue = `%${val}`;
  23. break;
  24. case 'Contains':
  25. transformedValue = `%${val}%`;
  26. break;
  27. case 'Matches':
  28. default:
  29. transformedValue = val;
  30. break;
  31. }
  32. return transformedValue;
  33. }
  34. };
  35. // Generate array from CSV string
  36. const toArrTag = (str: TemplateStringsArray): string[] => str[0].split(',').map(key => key.trim());
  37. // Pad array
  38. const arrayPad = (length: number) => (arr: string[]): any[] => [...arr, ...Array(length - arr.length).fill('')];
  39. // Utility function for casting an array to metadata (useful for components that render FormGroups)
  40. const arrayToMeta = array => array.map(val => ({ name: val, 'value' : val }));
  41. // Exclude 'fieldsToExclude' from obj, returning a new object
  42. // fieldsToExclude can be an array of field keys or a CSV of field keys
  43. const excludeFields = (obj: StringMap, fieldsToExclude: string | string[]) => {
  44. const ex = Array.isArray(fieldsToExclude) ? fieldsToExclude : fieldsToExclude.split(',').map(key => key.trim());
  45. return Object.entries(obj).reduce(
  46. (res, [key, val]) => ex.includes(key) ? res : { ...res, [key]: val },
  47. {}
  48. );
  49. }
  50. export { standardModifiers, standardTransformer, toArrTag, arrayPad, arrayToMeta, excludeFields };