demo/assets/Script/Common/GameUtil.ts

373 lines
11 KiB
TypeScript
Raw Normal View History

2024-03-22 00:57:47 -07:00
export default class GameUtil {
public static MONEY_PRECISION: number = 2;
public static parseUrlData(url: string = null) {
if (!url) {
url = window.location.href;
}
let iUrl = new URL(url);
let dataBase64 = iUrl.searchParams.get("data");
if (dataBase64 === null || dataBase64.length <= 0) {
dataBase64 = "eyJlbnYiOiJkZXYiLCJzZXJ2ZXIiOiJodHRwczovL2dhbWVkZXYuYm53LnZlbnR1cmVzIiwic3VicGF0aCI6Ii90cnVjby9hcGkiLCJ0b2tlbiI6IjA3YjQyMDg1LWYyMjUtNDQ5My1iNjcxLWZmNmQ1ODE4ZDM0OSIsImdhbWVDb2RlIjoiVFJVQ08iLCJnYW1lSWQiOjEzLCJ1c2VybmFtZSI6ImN1b25nbm0iLCJjdXJyZW5jeSI6IlVTRCIsImlwIjoiMTI3LjAuMC4xIiwibGFuZ3VhZ2UiOiJlbiIsIm9wZXJhdG9yIjoibmZndXNkIiwidGltZXN0YW1wIjoiMTY5ODIwNjk4NyIsInBsYXltb2RlIjoiZnJlZSIsInNpZ25hdHVyZSI6IjM0Y2M5NDgxNjBiZGFhNWE1NmFmZmU2N2NmYThhZjU3OTdkZDUwYTA3MTQ2ZTliYTA0ZGQzMjIzMzFjZjc0NjIifQ"
}
if (dataBase64) {
let dataDecode = atob(dataBase64);
return JSON.parse(dataDecode);
}
return null;
}
public static Number(val: string): number {
return Number(val.replace(',', ''));
}
public static getRandomInt(min: number, max: number): number {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
}
public static getNewWidth(originWidth: number, originHeight: number, newHeight: number): number {
return newHeight * originWidth / originHeight
}
static isNum(string: string): boolean {
return /\d/.test(string);
}
private static TIMES = [
["Second", 1],
["Minute", 60],
["Hour", 3600],
["Day", 86400],
["Week", 604800],
["Month", 2592000],
["Year", 31536000],
];
public static formatMoneyBet(money) {
if (Number.isInteger(money)) {
return this.formatMoney(money);
}
money = Number(money.toFixed(GameUtil.MONEY_PRECISION));
return this.formatMoney(money);
}
public static formatMoney(money) {
// let num = GameUtil.round(money,2);
let multiplier = Math.pow(10, GameUtil.MONEY_PRECISION); // số mũ của 10 cần nhân vào a trước khi làm tròn
let num = Math.floor(money * multiplier) / multiplier; // giữ lại precision số chữ số sau dấu thập phân
var price = num.toFixed(2).split(".");
if (price.length <= 0) {
price[0] = num.toString();
}
let thousands = price[0].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
let decimalPlaces = '';
if (price.length > 1) {
decimalPlaces += price[1];
if (decimalPlaces == '00') {
return thousands.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
}
return thousands.replace(/\B(?=(\d{3})+(?!\d))/g, ",") + '.' + decimalPlaces;
}
public static round2(num: number, decimalPlaces = 2) {
if (num == null || num == undefined) {
return '';
}
const str = num.toString();
if (str.includes('.')) {
const arr = str.split('.');
if (arr.length > 1) {
if (arr[1].length <= decimalPlaces) {
return num;
}
}
}
let number2 = parseFloat(num.toString());
let multiplier = Math.pow(10, decimalPlaces);
const returnValue = Math.floor(number2 * multiplier) / multiplier;
return returnValue;
}
public static round(num: number, decimalPlaces = 0) {
var p = Math.pow(10, decimalPlaces);
var n = (num * p) * (1 + Number.EPSILON);
return Math.round(n) / p;
}
public static dateFormat = (miliseconds: number, isHour: boolean) => {
if (miliseconds == undefined || miliseconds === 0) {
return "_";
}
let date = new DateUtil(miliseconds);
if (
date.customFormat("#YYYY#") == "1970" ||
date.customFormat("#YYYY#") == "9999"
) {
return "_";
}
if (isHour) {
return date.customFormat("#hh#:#mm#");
}
return date.customFormat("#DD#-#MM#-#YYYY#");
};
public static formatTime(milisecond: number) {
var seconds = Math.floor((milisecond / 1000) % 60);
var minutes = Math.floor((milisecond / (60 * 1000)) % 60);
var hours = Math.floor((milisecond / (60 * 60 * 1000)) % 60);
return this.pad(hours) + ":" + this.pad(minutes) + ":" + this.pad(seconds);
}
public static formatTimeHhMmsS(date: Date) {
return this.pad(date.getHours()) + ":" + this.pad(date.getMinutes()) + ":" + this.pad(date.getSeconds());
}
public static formatTimeDdMName(d: Date) {
const day = d.getDate();
const month = d.toLocaleString('default', { month: 'short' });
return `${day} ${month}`;;
}
public static pad(d) {
return d < 10 ? "0" + d.toString() : d.toString();
}
public static timeAgo(time: number): any {
for (var t = 0; t < GameUtil.TIMES.length; t++) {
if (time < Number(GameUtil.TIMES[t][1])) {
if (t == 0) {
return "0 Second";
} else {
time = Math.round(time / <any>GameUtil.TIMES[t - 1][1]);
return time + " " + GameUtil.TIMES[t - 1][0];
}
}
}
}
public static nameSplit(name: string, numSplit: number = 8): string {
if (name.length > numSplit) {
return name.substring(0, numSplit - 3) + '...';
}
return name;
}
public static radiansToDegrees(radian: number): number {
var pi = Math.PI;
return radian * (180 / pi);
}
public static time_format(d): string {
let hours = GameUtil.format_two_digits(d.getHours());
let minutes = GameUtil.format_two_digits(d.getMinutes());
let seconds = GameUtil.format_two_digits(d.getSeconds());
return hours + ":" + minutes + ":" + seconds;
}
public static timeFormatH(dateObj: Date): string {
let year = dateObj.getFullYear();
let month = (dateObj.getMonth() + 1).toString();
month = ('0' + month).slice(-2);
// To make sure the month always has 2-character-formate. For example, 1 => 01, 2 => 02
let date = dateObj.getDate().toString();
date = ('0' + date).slice(-2);
// To make sure the date always has 2-character-formate
let hour = dateObj.getHours().toString();
hour = ('0' + hour).slice(-2);
// To make sure the hour always has 2-character-formate
let minute = dateObj.getMinutes().toString();
minute = ('0' + minute).slice(-2);
// To make sure the minute always has 2-character-formate
let second = dateObj.getSeconds().toString();
second = ('0' + second).slice(-2);
// To make sure the second always has 2-character-formate
// const time = `${date}/${month}/${year} ${hour}:${minute}:${second}`;
// let hours = dateObj.getHours() % 12;
// let ampm = dateObj.getHours() >= 12 ? 'PM' : 'AM';
const time = `${date}/${month}/${hour}:${minute}:${second}`;
// const time = `${hours}:${minute}:${second} ${ampm}`;
return time;
}
public static format_two_digits(n): string {
return n < 10 ? '0' + n : n;
}
public static removeTrailZero(numberString: string): string {
let trimmedString = numberString
if (numberString === '0.00') {
trimmedString = '0.0';
} else {
trimmedString = numberString.replace(/\.?0+$/, "");
}
return trimmedString;
}
public static formatNumberKBT(numberInput: number) {
let num = Number(numberInput.toString().replace(/[^0-9.]/g, ''));
if (num < 1000) {
return num;
}
let si = [
{ v: 1E3, s: "K" },
{ v: 1E6, s: "M" },
{ v: 1E9, s: "B" },
{ v: 1E12, s: "T" },
{ v: 1E15, s: "P" },
{ v: 1E18, s: "E" }
];
let index: number;
for (index = si.length - 1; index > 0; index--) {
if (num >= si[index].v) {
break;
}
}
return (num / si[index].v).toFixed(2).replace(/\.0+$|(\.[0-9]*[1-9])0+$/, "$1") + si[index].s;
};
public static capitalizeFirstLetter(string: string) {
if (string === undefined || string.length <= 0) {
return ''
}
return string.charAt(0).toUpperCase() + string.slice(1);
}
public static getIpServer(gameName: string = null): string {
let evn = '';
if (window.location.href) {
let url = new URL(window.location.href);
evn = url.searchParams.get("env");
gameName = url.searchParams.get("gameCode");
}
let ip = Config.IP_SERVER[gameName.toLowerCase()].trim();
if (evn == 'staging') {
let port = ip.split(":")[1];
if (!isNaN(port)) {
ip = `${Config.IP_SERVER_STAGING}:${port}`;
}
}
return ip;
}
2024-04-05 00:45:18 -07:00
public CSVToArray( strData, strDelimiter ) {
strDelimiter = (strDelimiter || ",");
var objPattern = new RegExp(
(
"(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
"([^\"\\" + strDelimiter + "\\r\\n]*))"
),
"gi"
);
var arrData = [[]];
var arrMatches = null;
while (arrMatches = objPattern.exec( strData )){
var strMatchedDelimiter = arrMatches[ 1 ];
if (
strMatchedDelimiter.length &&
(strMatchedDelimiter != strDelimiter)
){
arrData.push( [] );
}
if (arrMatches[ 2 ]){
var strMatchedValue = arrMatches[ 2 ].replace(
new RegExp( "\"\"", "g" ),
"\""
);
} else {
var strMatchedValue = arrMatches[ 3 ];
}
arrData[ arrData.length - 1 ].push( strMatchedValue );
}
if(arrData.length>0){
arrData.pop();
}
return arrData;
}
2024-03-22 00:57:47 -07:00
}
class DateUtil extends Date {
customFormat = function (formatString) {
var YYYY,
YY,
MMMM,
MMM,
MM,
M,
DDDD,
DDD,
DD,
D,
hhhh,
hhh,
hh,
h,
mm,
m,
ss,
s,
ampm,
AMPM,
dMod,
th;
YY = ((YYYY = this.getFullYear()) + "").slice(-2);
MM = (M = this.getMonth() + 1) < 10 ? "0" + M : M;
DD = (D = this.getDate()) < 10 ? "0" + D : D;
th =
D >= 10 && D <= 20
? "th"
: (dMod = D % 10) == 1
? "st"
: dMod == 2
? "nd"
: dMod == 3
? "rd"
: "th";
formatString = formatString
.replace("#YYYY#", YYYY)
.replace("#YY#", YY)
.replace("#MMMM#", MMMM)
.replace("#MM#", MM)
.replace("#M#", M)
.replace("#DDDD#", DDDD)
.replace("#DD#", DD)
.replace("#D#", D)
.replace("#th#", th);
h = hhh = this.getHours();
//if (h == 0) h = 24;
//if (h > 12) h -= 12;
hh = h < 10 ? "0" + h : h;
hhhh = hhh < 10 ? "0" + hhh : hhh;
//AMPM = (ampm = hhh < 12 ? 'am' : 'pm').toUpperCase();
AMPM = "";
mm = (m = this.getMinutes()) < 10 ? "0" + m : m;
ss = (s = this.getSeconds()) < 10 ? "0" + s : s;
return formatString
.replace("#hhhh#", hhhh)
.replace("#hhh#", hhh)
.replace("#hh#", hh)
.replace("#h#", h)
.replace("#mm#", mm)
.replace("#m#", m)
.replace("#ss#", ss)
.replace("#s#", s);
};
}