Source: functions/createMessage.js

  1. /**
  2. * simplePass - A JavaScript password generator.
  3. * Copyright (C) 2023 Jordan Vezina(staticBanter)
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. 'use strict';
  19. import config from "../simplePass.config.js";
  20. /**
  21. * @file
  22. * @module createMessage
  23. */
  24. /**
  25. * Creates a message using a template strings.
  26. *
  27. * @function createMessage
  28. * @param {string} templateString The template message string.
  29. * @param {Array<string>} replacements The template string replacements.
  30. * @param {string} [marker] The template marker to replace in the string.
  31. * @throws Will throw an error a message replacement contains a template marker.
  32. * @requires config
  33. * @returns {string} The message with the template markers replaced.
  34. */
  35. export default function createMessage(templateString, replacements, cFig = config) {
  36. // * Note: Please do not use this function to create it's own error messages, as this could be... problematic.
  37. // Initialize our character index.
  38. let index = 0;
  39. templateString = `${cFig.messages.prefix} ${templateString}`;
  40. while (templateString.includes(cFig.messages.templateMarker)) {
  41. // Check if the replacement contains a marker. This will cause infinite looping.
  42. if (replacements[index] === cFig.messages.templateMarker) {
  43. throw new Error(`${cFig.messages.prefix}-cM_E.1: A \'Message Replacement\', "${replacements[index]}", contained a \'Message Marker\', "${cFig.messages.templateMarker}".`);
  44. }
  45. /**
  46. * If we have a replacement at that index replace the marker with that one.
  47. * Else replace it with the last replacement in the list.
  48. * @ignore
  49. */
  50. templateString = templateString.replace(cFig.messages.templateMarker, replacements[index++] ?? replacements[(replacements.length - 1)]);
  51. }
  52. // Return the string.
  53. return templateString;
  54. }