stringUtils.ts 1.6 KB

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