Utils.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 rangeMinInteger: number = 10000,
  46. rangeMaxInteger: number = 99999999,
  47. prefix: string = '_0x';
  48. return `${prefix}${(Utils.decToHex(Utils.getRandomInteger(rangeMinInteger, rangeMaxInteger))).substr(0, length)}`;
  49. }
  50. /**
  51. * @param string
  52. * @returns {string}
  53. */
  54. public static stringToUnicode (string: string): string {
  55. return `'${string.replace(/[\s\S]/g, (escape) => {
  56. return `\\u${('0000' + escape.charCodeAt(0).toString(16)).slice(-4)}`;
  57. })}'`;
  58. }
  59. }