makeConfig.js.flow 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import _ from 'lodash';
  2. import getBorderCharacters from './getBorderCharacters';
  3. import validateConfig from './validateConfig';
  4. import calculateMaximumColumnWidthIndex from './calculateMaximumColumnWidthIndex';
  5. /**
  6. * Merges user provided border characters with the default border ("honeywell") characters.
  7. *
  8. * @param {Object} border
  9. * @returns {Object}
  10. */
  11. const makeBorder = (border = {}) => {
  12. return Object.assign({}, getBorderCharacters('honeywell'), border);
  13. };
  14. /**
  15. * Creates a configuration for every column using default
  16. * values for the missing configuration properties.
  17. *
  18. * @param {Array[]} rows
  19. * @param {Object} columns
  20. * @param {Object} columnDefault
  21. * @returns {Object}
  22. */
  23. const makeColumns = (rows, columns = {}, columnDefault = {}) => {
  24. const maximumColumnWidthIndex = calculateMaximumColumnWidthIndex(rows);
  25. _.times(rows[0].length, (index) => {
  26. if (_.isUndefined(columns[index])) {
  27. columns[index] = {};
  28. }
  29. columns[index] = Object.assign({
  30. alignment: 'left',
  31. paddingLeft: 1,
  32. paddingRight: 1,
  33. truncate: Infinity,
  34. width: maximumColumnWidthIndex[index],
  35. wrapWord: false
  36. }, columnDefault, columns[index]);
  37. });
  38. return columns;
  39. };
  40. /**
  41. * Makes a new configuration object out of the userConfig object
  42. * using default values for the missing configuration properties.
  43. *
  44. * @param {Array[]} rows
  45. * @param {Object} userConfig
  46. * @returns {Object}
  47. */
  48. export default (rows, userConfig = {}) => {
  49. validateConfig('config.json', userConfig);
  50. const config = _.cloneDeep(userConfig);
  51. config.border = makeBorder(config.border);
  52. config.columns = makeColumns(rows, config.columns, config.columnDefault);
  53. if (!config.drawHorizontalLine) {
  54. /**
  55. * @returns {boolean}
  56. */
  57. config.drawHorizontalLine = () => {
  58. return true;
  59. };
  60. }
  61. if (config.singleLine === undefined) {
  62. config.singleLine = false;
  63. }
  64. return config;
  65. };