utils.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // @ts-check
  2. const FALSE_VALUES = [
  3. false,
  4. 0,
  5. '0',
  6. 'f',
  7. 'F',
  8. 'false',
  9. 'FALSE',
  10. 'off',
  11. 'OFF',
  12. ];
  13. /**
  14. * @param {any} value
  15. * @returns {boolean}
  16. */
  17. export function isTruthy(value) {
  18. return value && !FALSE_VALUES.includes(value);
  19. }
  20. /**
  21. * See app/lib/ascii_folder.rb for the canon definitions
  22. * of these constants
  23. */
  24. const NON_ASCII_CHARS = 'ÀÁÂÃÄÅàáâãäåĀāĂ㥹ÇçĆćĈĉĊċČčÐðĎďĐđÈÉÊËèéêëĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħÌÍÎÏìíîïĨĩĪīĬĭĮįİıĴĵĶķĸĹĺĻļĽľĿŀŁłÑñŃńŅņŇňʼnŊŋÒÓÔÕÖØòóôõöøŌōŎŏŐőŔŕŖŗŘřŚśŜŝŞşŠšſŢţŤťŦŧÙÚÛÜùúûüŨũŪūŬŭŮůŰűŲųŴŵÝýÿŶŷŸŹźŻżŽž';
  25. const EQUIVALENT_ASCII_CHARS = 'AAAAAAaaaaaaAaAaAaCcCcCcCcCcDdDdDdEEEEeeeeEeEeEeEeEeGgGgGgGgHhHhIIIIiiiiIiIiIiIiIiJjKkkLlLlLlLlLlNnNnNnNnnNnOOOOOOooooooOoOoOoRrRrRrSsSsSsSssTtTtTtUUUUuuuuUuUuUuUuUuUuWwYyyYyYZzZzZz';
  26. /**
  27. * @param {string} str
  28. * @returns {string}
  29. */
  30. export function foldToASCII(str) {
  31. const regex = new RegExp(NON_ASCII_CHARS.split('').join('|'), 'g');
  32. return str.replace(regex, function(match) {
  33. const index = NON_ASCII_CHARS.indexOf(match);
  34. return EQUIVALENT_ASCII_CHARS[index];
  35. });
  36. }
  37. /**
  38. * @param {string} str
  39. * @returns {string}
  40. */
  41. export function normalizeHashtag(str) {
  42. return foldToASCII(str.normalize('NFKC').toLowerCase()).replace(/[^\p{L}\p{N}_\u00b7\u200c]/gu, '');
  43. }
  44. /**
  45. * @param {string|string[]} arrayOrString
  46. * @returns {string}
  47. */
  48. export function firstParam(arrayOrString) {
  49. if (Array.isArray(arrayOrString)) {
  50. return arrayOrString[0];
  51. } else {
  52. return arrayOrString;
  53. }
  54. }
  55. /**
  56. * Takes an environment variable that should be an integer, attempts to parse
  57. * it falling back to a default if not set, and handles errors parsing.
  58. * @param {string|undefined} value
  59. * @param {number} defaultValue
  60. * @param {string} variableName
  61. * @returns {number}
  62. */
  63. export function parseIntFromEnvValue(value, defaultValue, variableName) {
  64. if (typeof value === 'string' && value.length > 0) {
  65. const parsedValue = parseInt(value, 10);
  66. if (isNaN(parsedValue)) {
  67. throw new Error(`Invalid ${variableName} environment variable: ${value}`);
  68. }
  69. return parsedValue;
  70. } else {
  71. return defaultValue;
  72. }
  73. }