ArrayUtils.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import { injectable, inject } from 'inversify';
  2. import { ServiceIdentifiers } from '../container/ServiceIdentifiers';
  3. import { IArrayUtils } from '../interfaces/utils/IArrayUtils';
  4. import { IRandomGenerator } from '../interfaces/utils/IRandomGenerator';
  5. @injectable()
  6. export class ArrayUtils implements IArrayUtils {
  7. /**
  8. * @type {IRandomGenerator}
  9. */
  10. private readonly randomGenerator: IRandomGenerator;
  11. /**
  12. * @param randomGenerator
  13. */
  14. constructor (
  15. @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator
  16. ) {
  17. this.randomGenerator = randomGenerator;
  18. }
  19. /**
  20. * @param length
  21. * @return {number[]}
  22. */
  23. public arrayRange (length: number): number[] {
  24. const range: number[] = [];
  25. for (let i: number = 0; i < length; i++) {
  26. range.push(i);
  27. }
  28. return range;
  29. }
  30. /**
  31. * @param array
  32. * @param times
  33. * @returns {T[]}
  34. */
  35. public arrayRotate <T> (array: T[], times: number): T[] {
  36. if (!array.length) {
  37. throw new ReferenceError(`Cannot rotate empty array.`);
  38. }
  39. if (times <= 0) {
  40. return array;
  41. }
  42. const newArray: T[] = array;
  43. let temp: T | undefined;
  44. while (times--) {
  45. temp = newArray.pop()!;
  46. newArray.unshift(temp);
  47. }
  48. return newArray;
  49. }
  50. /**
  51. * @param array
  52. * @return {T[]}
  53. */
  54. public arrayShuffle <T> (array: T[]): T[] {
  55. const shuffledArray: T[] = [...array];
  56. for (let i: number = shuffledArray.length; i; i--) {
  57. const j: number = Math.floor(this.randomGenerator.getMathRandom() * i);
  58. [shuffledArray[i - 1], shuffledArray[j]] = [shuffledArray[j], shuffledArray[i - 1]];
  59. }
  60. return shuffledArray;
  61. }
  62. }