Utils.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. export class Utils {
  2. /**
  3. * @param array
  4. * @param times
  5. * @param reverse
  6. * @returns any[]
  7. */
  8. public static arrayRotate (array: any[], times: number, reverse: boolean = false): any[] {
  9. if (times < 0) {
  10. return;
  11. }
  12. let newArray: any[] = array,
  13. temp: any;
  14. while (times--) {
  15. if (!reverse) {
  16. temp = newArray.pop();
  17. newArray.unshift(temp);
  18. } else {
  19. temp = newArray.shift();
  20. newArray.push(temp);
  21. }
  22. }
  23. return newArray;
  24. }
  25. /**
  26. * @param dec
  27. * @returns {string}
  28. */
  29. public static decToHex(dec: number): string {
  30. return (dec + Math.pow(16, 6)).toString(16).substr(-6);
  31. }
  32. /**
  33. * @param min
  34. * @param max
  35. * @returns {number}
  36. */
  37. public static getRandomInteger(min: number, max: number): number {
  38. return Math.floor(Math.random() * (max - min + 1)) + min;
  39. }
  40. /**
  41. * @param length
  42. * @returns any
  43. */
  44. public static getRandomVariableName (length: number = 6): string {
  45. const prefix = '_0x';
  46. return `${prefix}${(Utils.decToHex(Utils.getRandomInteger(10000, 99999999))).substr(0, length)}`;
  47. }
  48. /**
  49. * @param string
  50. * @returns {string}
  51. */
  52. public static stringToUnicode (string: string): string {
  53. return `'${string.replace(/[\s\S]/g, (escape) => {
  54. return `\\u${('0000' + escape.charCodeAt(0).toString(16)).slice(-4)}`;
  55. })}'`;
  56. }
  57. }