StringUtils.js

  1. import { randomPick } from './ArrayUtils'
  2. /**
  3. * @module StringUtils
  4. */
  5. /**
  6. * @function generateRandom
  7. * @description Generate a random string from a number of character and a pool of
  8. * @param {Number} [l=6] string length
  9. * @param {String[]} pool possible characters to generate the string
  10. *
  11. * @returns {String}
  12. */
  13. export const generateRandom = (l = 6, pool) => {
  14. if (typeof l != 'number')
  15. return;
  16. if (!pool || !Array.isArray(pool) || pool.length == 0)
  17. pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789$*#&!'.split('');
  18. let s = '';
  19. for (let i = 0; i < l; i++) {
  20. s += randomPick(pool);
  21. }
  22. return s;
  23. }
  24. /**
  25. * @function capitalize
  26. * @description turn first character of a string to uppercase
  27. * @param {String} s
  28. */
  29. export const capitalize = s => {
  30. return s && s[0].toUpperCase() + s.slice(1);
  31. }
  32. /**
  33. * @function unCapitalize
  34. * @description turn first character of a string to lowercase
  35. * @param {String} s
  36. *
  37. * @returns {String}
  38. */
  39. export const unCapitalize = s => {
  40. return s && s[0].toLowerCase() + s.slice(1);
  41. }
  42. /**
  43. * @function capitalizeWords
  44. * @description turn each word first letter to uppercase
  45. * @param {String} s string to transform
  46. *
  47. * @returns {String}
  48. */
  49. export const capitalizeWords = s => {
  50. return s.split(' ').map(s => capitalize(s)).join(' ');
  51. }
  52. /**
  53. * @function replaceAll
  54. * @description replace all occurrences of a search with a replacement in a String
  55. * @param {String} str
  56. * @param {String} search
  57. * @param {String} replacement
  58. *
  59. * @returns {String}
  60. */
  61. export const replaceAll = (str, search, replacement) => {
  62. return str.replace(new RegExp(search, 'g'), replacement);
  63. }
  64. /**
  65. * @function stringToFunction
  66. * @description Returns a function from a string property path
  67. * @param {String} str
  68. * @returns {Function} function
  69. * @example
  70. * //returns addEventListener
  71. * stringToFunction("window.addEventListener");
  72. */
  73. export const stringToFunction = str => {
  74. let arr = str.split("."),
  75. fn = (global || this);
  76. for (let i = 0, len = arr.length; i < len; i++) {
  77. fn = fn[arr[i]];
  78. }
  79. if (typeof fn !== "function") {
  80. throw new TypeError("function not found");
  81. }
  82. return fn;
  83. }
  84. /**
  85. * @function secsToMin
  86. * @description transform a number in seconds in a string
  87. *
  88. * @param {Number} d Seconds integer
  89. *
  90. * @return {String} string in format hh:mm:ss
  91. */
  92. export const secsToMin = d => {
  93. let hrs = ~~(d / 3600);
  94. let mins = ~~((d % 3600) / 60);
  95. let secs = ~~d % 60;
  96. // Output like "1:01" or "4:03:59" or "123:03:59"
  97. let ret = "";
  98. if (hrs > 0) {
  99. ret += "" + hrs + ":" + (mins < 10 ? "0" : "");
  100. }
  101. ret += "" + mins + ":" + (secs < 10 ? "0" : "");
  102. ret += "" + secs;
  103. return ret;
  104. }
  105. /**
  106. * @function nFormatter
  107. * @description format a number in counterpart unit
  108. * @param {Number} num number to transform
  109. * @param {Number} [digits=0] number of decimal digits
  110. * @example
  111. * //returns "10M"
  112. * nFormatter(10000000)
  113. */
  114. export const nFormatter = (num, digits = 0) => {
  115. const si = [
  116. { value: 1, symbol: "" },
  117. { value: 1E3, symbol: "k" },
  118. { value: 1E6, symbol: "M" },
  119. { value: 1E9, symbol: "G" },
  120. { value: 1E12, symbol: "T" },
  121. { value: 1E15, symbol: "P" },
  122. { value: 1E18, symbol: "E" }
  123. ];
  124. const rx = /\.0+$|(\.[0-9]*[1-9])0+$/;
  125. let i;
  126. for (i = si.length - 1; i > 0; i--) {
  127. if (num >= si[i].value) {
  128. break;
  129. }
  130. }
  131. return (num / si[i].value).toFixed(digits).replace(rx, "$1") + si[i].symbol;
  132. }
  133. /**
  134. * @function encodeHTML
  135. * @description replace characters like chevrons in html string
  136. *
  137. * @param {String} s
  138. *
  139. * @returns {String}
  140. */
  141. export const encodeHTML = s => {
  142. return typeof s == 'string'
  143. ? s
  144. .replace(/&/g, '&amp;')
  145. .replace(/</g, '&lt;')
  146. .replace(/"/g, '&quot;')
  147. : s;
  148. }
  149. /**
  150. * @function generateHexKey
  151. * @description code date timestamp in hexadecimal string
  152. *
  153. * @returns {String}
  154. * @example
  155. * // current time: 1590247414800
  156. * // returns "1724221dc10"
  157. * generateHexKey()
  158. */
  159. export const generateHexKey = () => String((new Date).getTime().toString(16))
  160. export default {
  161. capitalize,
  162. capitalizeWords,
  163. generateRandom,
  164. replaceAll,
  165. secsToMin,
  166. stringToFunction,
  167. unCapitalize,
  168. nFormatter,
  169. encodeHTML,
  170. generateHexKey,
  171. }