Utils.ts 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. export class Utils {
  2. /**
  3. * 随机数 (包含min,不包含max)
  4. * @param min
  5. * @param max
  6. * @param isInt
  7. * @return {*}
  8. */
  9. public static getRandom(min: number = 0, max: number = 1, isInt: boolean = false): number {
  10. if (min == null) min = 0;
  11. if (max == null) max = 1;
  12. if (isInt == null) isInt = false;
  13. if (min === max) return min;
  14. let value = min + (Math.random() * (max - min));
  15. if (isInt) {
  16. value = Math.floor(value);
  17. }
  18. return value;
  19. }
  20. /**
  21. * 随机整数-包含最大值,最小值
  22. * @param min
  23. * @param max
  24. * @return {*}
  25. */
  26. public static getRandomIntInclusive(min: number, max: number) {
  27. min = Math.ceil(min);
  28. max = Math.floor(max);
  29. if (min == max)
  30. return min;
  31. return Math.floor(Math.random() * (max - min + 1)) + min; //The maximum is inclusive and the minimum is inclusive
  32. }
  33. /**
  34. * 随机整数-不包含最大值,最小值
  35. * @param min
  36. * @param max
  37. * @return {*}
  38. */
  39. public static getRandomInt(min: number, max: number):number {
  40. min = Math.ceil(min); max = Math.ceil(max);
  41. return Math.floor(Math.random() * (max - min)) + min;
  42. }
  43. /** */
  44. public static getRandomNumberInRange(min:number, max:number):number {
  45. return Math.random() * (max - min) + min;
  46. }
  47. /**生成随机整数 -1 或 1*/
  48. public static getRandomDir():number {
  49. return Math.floor(Math.random() * 2) === 0 ? -1 : 1;//
  50. }
  51. /**
  52. * 在指定数组中随机取出N个不重复的数据
  53. * @param resArr
  54. * @param ranNum
  55. * @returns {Array}
  56. */
  57. public static getRandomDiffValueFromArr<T>(resArr: Array<T>, ranNum: number): Array<T> {
  58. let arr = new Array<T>();
  59. let result = new Array<T>();
  60. if (!resArr || resArr.length <= 0 || ranNum <= 0) {
  61. return result;
  62. }
  63. for (let i = 0; i < resArr.length; i++) {
  64. arr.push(resArr[i]);
  65. }
  66. if (ranNum >= arr.length) {
  67. return arr;
  68. }
  69. ranNum = Math.min(ranNum, arr.length - 1);
  70. for (let i = 0; i < ranNum; i++) {
  71. let ran = Utils.getRandomIntInclusive(0, arr.length - 1);// Math.floor(Math.random() * arr.length);
  72. result.push(arr.splice(ran, 1)[0]);
  73. }
  74. return result;
  75. }
  76. /**
  77. * 随机一个字符串
  78. * @param length
  79. * @returns
  80. */
  81. public static randomStr(length: number): string {
  82. let result: string = '';
  83. const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  84. const charactersLength = characters.length;
  85. for (let i = 0; i < length; i++) {
  86. result += characters.charAt(Math.floor(Math.random() * charactersLength));
  87. }
  88. return result;
  89. }
  90. /**
  91. * 时间转换 毫秒=》2019-03-28 19:55:34
  92. * @param milliseconds
  93. * @return {string}
  94. */
  95. public static time2str (milliseconds: number): string {
  96. let time = new Date();
  97. time.setTime(milliseconds);
  98. let year = time.getFullYear();
  99. let hours = time.getHours();
  100. let min = time.getMinutes();
  101. let sec = time.getSeconds();
  102. let month = time.getMonth()+1;
  103. let date = time.getDate();
  104. return year +"-"+ month + "-" + date + " " + (hours > 9 ? hours : "0" + hours) + ":" + (min > 9 ? min : "0" + min) + ":" + (sec > 9 ? sec : "0" + sec);
  105. }
  106. /**
  107. * 将毫秒转换为时间格式 00:00:00
  108. * @param delay
  109. * @param detail
  110. * @return
  111. */
  112. public static second2time (delay: number, detail: number = 2): string {
  113. // if (detail == undefined) detail = 2;
  114. //天
  115. let d = Math.floor(delay / 86400000);
  116. delay = delay % 86400000;
  117. // 小时
  118. let h = Math.floor(delay / 3600000);
  119. delay = delay % 3600000;
  120. // 分钟
  121. let m = Math.floor(delay / 60000);
  122. delay = delay % 60000;
  123. // 秒
  124. let s = Math.floor(delay / 1000);
  125. delay = delay % 1000;
  126. // 毫秒
  127. let ml = delay;
  128. let result: string = "";
  129. if (d > 0 && detail > 0) {
  130. result += (d > 9 ? d : "0" + d) + ":";// "天";
  131. detail--;
  132. }
  133. if (h > 0 && detail > 0) {
  134. result += (h > 9 ? h : "0" + h) + ":";// "小时";
  135. detail--;
  136. }
  137. if (m > 0 && detail > 0) {
  138. result += (m > 9 ? m : "0" + m) + ":";// "分钟";
  139. detail--;
  140. }
  141. if (detail > 0) {
  142. result += (s > 9 ? s : "0" + s);// "秒";
  143. detail--;
  144. }
  145. if (ml > 0 && detail > 0) {
  146. detail--;
  147. }
  148. return result;
  149. }
  150. public static formatMilliseconds(milliseconds: number): string {
  151. const seconds = Math.floor((milliseconds / 1000) % 60);
  152. const minutes = Math.floor((milliseconds / (1000 * 60)) % 60);
  153. const hours = Math.floor((milliseconds / (1000 * 60 * 60)) % 24);
  154. //const formattedSeconds = seconds < 10 ? "0" + seconds : seconds;
  155. //const formattedMinutes = minutes < 10 ? "0" + minutes : minutes;
  156. //const formattedHours = hours < 10 ? "0" + hours : hours;
  157. //`${formattedHours}:${formattedMinutes}:${formattedSeconds}`;
  158. return `${hours.toString().padStart(2, "0")}:${minutes.toString().padStart(2,"0")}:${seconds.toString().padStart(2,"0")}`;
  159. }
  160. /**
  161. * 取小数位
  162. * @param decimal 小数
  163. * @param places 位数
  164. * @return {number}
  165. */
  166. public static getDecimal (decimal: number, places: number): number {
  167. let round: number = Math.pow(10, places);
  168. return Math.round(decimal * round) / round;
  169. }
  170. /**
  171. * 本年第几周
  172. * @param timestamp 毫秒
  173. * @returns
  174. */
  175. public static getYearWeek(timestamp: number): number {
  176. // let nowDate: Date = new Date(date);
  177. // let firstDay: Date = new Date(date);
  178. // firstDay.setMonth(0);//设置1月
  179. // firstDay.setDate(1);//设置1号
  180. // let diffDays = Math.ceil((nowDate.valueOf() - firstDay.valueOf())/(24*60*60*1000));
  181. // return Math.ceil((diffDays + (firstDay.getDay() + 1 - 1)) / 7);
  182. let currentDate: Date = new Date(timestamp);
  183. let year: Date = new Date(currentDate.getFullYear(), 0, 1);
  184. let days: number = Math.floor((currentDate.valueOf() - year.valueOf()) / (24 * 60 * 60 * 1000));
  185. let week: number = Math.ceil(( currentDate.getDay() + 1 + days) / 7);
  186. return week;
  187. }
  188. /**
  189. * 是否是同一天
  190. * @param timeStampA
  191. * @param timeStampB
  192. * @return {boolean}
  193. */
  194. public static isSameDay(timeStampA: number, timeStampB: number): boolean {
  195. let dateA = new Date(timeStampA);
  196. dateA.setHours(0, 0, 0, 0);
  197. let dateB = new Date(timeStampB);
  198. dateB.setHours(0, 0, 0, 0);
  199. return (dateA.getTime() == dateB.getTime()) ? true : false;
  200. }
  201. //
  202. public static checkAndAdd<t1>(map:Map<t1,number>,k:t1,v:number){
  203. if(map.has(k)){
  204. map.set(k,map.get(k)+v);
  205. }else{
  206. map.set(k,v);
  207. }
  208. }
  209. //
  210. /**
  211. * 随机权重下标
  212. * @param weights 权重数组
  213. */
  214. static randomWeights(weights: number[]) {
  215. // 总权重值
  216. const totalWeight = weights.reduce((a, b) => a + b, 0);
  217. // 随机的权重值
  218. const randomWeight = this.getRandom(0, totalWeight);
  219. for (let index = 0, weight = 0; index < weights.length; index++) {
  220. weight += weights[index];
  221. if (weight >= randomWeight) {
  222. return index;
  223. }
  224. }
  225. return -1;
  226. }
  227. /**
  228. * 随机数组下标
  229. * @param array 数组
  230. */
  231. static randomArray<T>(array: T[]): number;
  232. /**
  233. * 根据权重随机数组下标
  234. * @param array 数组
  235. * @param weights 权重数组
  236. */
  237. static randomArray<T>(array: T[], weights: number[]): number;
  238. static randomArray(array: any[], weights?: number[]) {
  239. if (!weights) {
  240. const index = this.getRandom(0, array.length,true);
  241. return index;
  242. }
  243. return this.randomWeights(weights.slice(0, array.length));
  244. }
  245. }