stringUtils.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import crypto from 'crypto'
  2. export default class StringUtils {
  3. // Private constructor to prevent instantiation
  4. private constructor() {
  5. // This utility class is not meant to be instantiated
  6. }
  7. /**
  8. * Normalise une chaine de caractères en retirant la casse et les caractères spéciaux, à des fins de recherche
  9. * par exemple
  10. * @param s
  11. */
  12. public static normalize(s: string): string {
  13. return s
  14. .toLowerCase()
  15. .replace(/[éèẽëêēĕėęě]/g, 'e')
  16. .replace(/[çćĉċč]/g, 'c')
  17. .replace(/[îïĩìíīĭ]/g, 'i')
  18. .replace(/[àãâåáäāăą]/g, 'a')
  19. .replace(/[ĝğġģ]/g, 'g')
  20. .replace(/[ħĥ]/g, 'h')
  21. .replace(/[öôõó]/g, 'o')
  22. .replace(/[ûüũùú]/g, 'u')
  23. .replace(/[š]/g, 's')
  24. .replace(/[ÿý]/g, 'y')
  25. .replace(/[ž]/g, 'z')
  26. .replace(/-/g, ' ')
  27. .trim()
  28. }
  29. /**
  30. * Convertit le paramètre d'entrée en entier
  31. * A la différence de parseInt, cette méthode accepte aussi les nombres.
  32. * @param s
  33. */
  34. public static parseInt(s: string | number) {
  35. return typeof s === 'number' ? s : parseInt(s)
  36. }
  37. /**
  38. * Hash une chaine de caractères avec l'algorithme demandé
  39. *
  40. * @param input
  41. * @param algorithm
  42. */
  43. public static async hash(input: string, algorithm: string = 'SHA-256') {
  44. const textAsBuffer = new TextEncoder().encode(input)
  45. const isNode =
  46. typeof process !== 'undefined' &&
  47. process.versions != null &&
  48. process.versions.node != null
  49. const cryptoLib = isNode ? crypto : window.crypto
  50. const hashBuffer = await cryptoLib.subtle.digest(algorithm, textAsBuffer)
  51. const hashArray = Array.from(new Uint8Array(hashBuffer))
  52. return hashArray.map((item) => item.toString(16).padStart(2, '0')).join('')
  53. }
  54. }