lib/util.js

  1. /**
  2. * @file Miscellaneous utilities; mainly routines for strings
  3. * @author Antonio Olmo Titos <a@olmo-titos.info>
  4. * @exports lib/util
  5. */
  6. // Internal packages:
  7. const LOGGING = require('./logging');
  8. // Constants:
  9. const REGEX_VALID_ID = /^[\w\-.,()][\w \-.,()]*[\w\-.,()]$/,
  10. DAY_NAMES = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
  11. /**
  12. * Check if a string is a valid ID for an entity
  13. * @param {String} string - the candidate string
  14. * @returns {Boolean} whether the string is valid
  15. */
  16. const isValidID = function(string) {
  17. if (!string)
  18. LOGGING.warn(`“isValidID()”: no string to normalise`);
  19. else
  20. return (string && string.match(REGEX_VALID_ID));
  21. };
  22. /**
  23. * “Normalise” a string to use it as the ID of an entity
  24. * @param {String} string - the candidate string
  25. * @returns {String} the normalised string
  26. */
  27. const normaliseID = function(string) {
  28. if (!string)
  29. LOGGING.warn(`“util.normaliseID()”: no string to normalise`);
  30. else if (!string.match(REGEX_VALID_ID))
  31. LOGGING.warn(`“util.normaliseID()”: “${string}” is not a valid ID string`);
  32. else
  33. return string.toLowerCase();
  34. };
  35. /**
  36. * Format a duration in minutes as a more readable string
  37. * @param {Number} duration - duration, in min (eg, 150)
  38. * @returns {String} the equivalent "nice" duration (eg, "1h30'")
  39. */
  40. const formatDuration = function(duration, forceSign) {
  41. if ('number' !== typeof duration)
  42. return '[unknown]';
  43. else if (0 === duration)
  44. return '0';
  45. else {
  46. const time = Math.abs(Math.round(duration)),
  47. h = Math.abs(Math.floor(duration / 60)),
  48. hs = h ? `${h}h` : '',
  49. m = time % 60,
  50. ms = m ? `${m}&prime;` : '',
  51. sign = duration < 0 ? '&minus;' : (forceSign ? '&plus;' : '');
  52. return `${sign}${hs}${ms}`;
  53. }
  54. };
  55. /**
  56. * Pre-process an entity item, or a list of entity items, to extend information
  57. * @param {Object} data - meeting info
  58. * @param {Object} the same object, perhaps extended with more info
  59. */
  60. const processData = function(data) {
  61. for (const i in data) {
  62. if (data[i].duration)
  63. data[i].niceDuration = formatDuration(data[i].duration);
  64. if (data[i].day)
  65. data[i].niceDay = DAY_NAMES[data[i].day];
  66. }
  67. };
  68. // Export stuff
  69. exports.isValidID = isValidID;
  70. exports.normaliseID = normaliseID;
  71. exports.processData = processData;
  72. exports.formatDuration = formatDuration;