Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { MONTH_NAME, MIN_SHOWN_DISCOUNT_PERCENT, MONTH_SHORT_NAME } from 'Helpers/constants';
- import { osName, OsTypes, osVersion, browserVersion, browserName, BrowserTypes, isChrome } from 'react-device-detect';
- import copy from 'copy-to-clipboard';
- import { config } from 'Config/config';
- import { ITranslation, translateText, REGION_CODE } from './translation-helper';
- import { IRegionData } from 'Redux/reducers/region';
- import { IForeignExchangeRate } from './foreign-exchange-helper';
- export function getStatic(fileName: string) {
- return '/static/' + fileName;
- }
- export function getAbsoluteUrl(path?: string) {
- const slashedPath = path ? (path.startsWith('/') ? path : '/' + path) : '';
- return window.location.origin + slashedPath;
- }
- export function getClientSideValue<T>(value: T, deffaultFalue: T): T {
- return typeof window !== 'undefined' ? value : deffaultFalue;
- }
- export function isNullOrUndefinedHelper(object: any): object is null | undefined {
- return object === undefined || object === null;
- }
- export const isset = (input: any): boolean => {
- return input !== undefined && input !== null;
- };
- export const getDefault = <T>(input: any, def: T): T => {
- return isset(input) ? input : def;
- };
- export const safeCall = <T extends (...args: any[]) => any>(
- fn: T | null | undefined,
- ...args: Parameters<T>
- ): ReturnType<T> | undefined => {
- return fn && fn(...args);
- };
- export function isObjectEmptyHelper(obj: object) {
- if (!obj || typeof obj !== 'object') return true;
- return Object.keys(obj).length === 0;
- }
- export const isJson = (value: any) => {
- if (
- value !== undefined &&
- value !== '' &&
- value !== 0 &&
- /^[\],:{}\s]*$/.test(
- value
- .replace(/\\["\\/bfnrtu]/g, '@')
- .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?/g, ']')
- .replace(/(?:^|:|,)(?:\s*\[)+/g, ''),
- )
- ) {
- return true;
- } else {
- return false;
- }
- };
- export const getJson = (value: any) => {
- if (isJson(value)) {
- return JSON.parse(value);
- } else {
- return value;
- }
- };
- export function titleCase(str: string) {
- if (!str || typeof str !== 'string') return str;
- const splitStr = str.replace(/_/g, ' ').toLowerCase().split(' ');
- for (let i = 0; i < splitStr.length; i++) {
- splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);
- }
- return splitStr.join(' ');
- }
- export function titleCaseUnder(str: string) {
- if (!str || typeof str !== 'string') return str;
- const splitStr = str.replace(/-/g, ' ').toLowerCase().split(' ');
- for (let i = 0; i < splitStr.length; i++) {
- splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);
- }
- return splitStr.join(' ');
- }
- export function titleCaseFromCamelCase(str: string) {
- if (!str || typeof str !== 'string') return str;
- let result = str.replace(/([A-Z]+)/g, ' $1').replace(/([A-Z][a-z])/g, ' $1');
- result = result.charAt(0).toUpperCase() + result.substring(1);
- return result;
- }
- export function arrayMessage(inputData: { [rule: string]: string[] }) {
- const properties = Object.keys(inputData);
- let message = '';
- for (const i of properties) {
- message = i + ' ' + inputData[i];
- }
- return message;
- }
- export function errorMessage(errData: { [rule: string]: any }, fieldName = 'errorMessage') {
- const properties = Object.keys(errData);
- let message = '';
- for (const i of properties) {
- if (typeof errData[i][fieldName] !== 'undefined') {
- message = message + errData[i][fieldName] + ' ';
- }
- }
- return message;
- }
- export function numberLimit(nmb: number, nmbMax: number, nmbMin = 1) {
- if (nmb > nmbMax) {
- return nmbMax;
- } else if (nmb < nmbMin) {
- return nmbMin;
- }
- return nmb;
- }
- export function getValue(value: any, defaultVal: any = null) {
- return typeof value === 'undefined' ? defaultVal : value;
- }
- export function getValueBoolean(value: any) {
- return typeof value === 'undefined' ? false : value;
- }
- export function issetValue(value: any) {
- return value === undefined || value === null ? false : value;
- }
- export function getObjRefVal(
- objVal: any[], // Haystack
- ref: string,
- idx: number,
- key = 'id',
- ): any {
- for (const val of objVal) {
- if (val[key] !== undefined && val[key] === idx) {
- return val[ref];
- }
- }
- return null;
- }
- export function getObjectValue(
- val: any, // Haystack
- key: string | string[], // Needle
- defVal: any = null, // Default Value
- ): any {
- const datChk = typeof key === 'string' ? [key] : key;
- const isValid = val !== undefined && val[datChk[0]] !== undefined;
- const result = isValid ? val[datChk[0]] : defVal;
- if (isValid && datChk.length > 1) {
- return getObjectValue(result, datChk.slice(1), defVal);
- }
- return result;
- }
- export function removeDuplicate(arrVal: string[]): any {
- return [...new Set(arrVal)];
- }
- export function getJsonStorageData(name: string, defaultVal: any): any {
- const storageData = localStorage.getItem(name);
- return storageData !== null && isJson(storageData) ? JSON.parse(storageData) : defaultVal;
- }
- export function setJsonStorageData(name: string, val: any): any {
- return localStorage.setItem(name, JSON.stringify(val));
- }
- export const moneyDot = (num: any | undefined | null) => {
- if (num === null || num === undefined) {
- return '';
- } else if (num === 0) {
- return 0;
- }
- const str = num.toString().split('.');
- if (str[0].length >= 4) {
- str[0] = str[0].replace(/(\d)(?=(\d{3})+$)/g, '$1.');
- }
- if (str[1] && str[1].length >= 4) {
- str[1] = str[1].replace(/(\d{3})/g, '$1 ');
- }
- return str.join(',');
- };
- export const dynamicSort = (property: any) => {
- let sortOrder = 1;
- if (property[0] === '-') {
- sortOrder = -1;
- property = property.substr(1);
- }
- return (a: any, b: any) => {
- const result = a[property] < b[property] ? -1 : a[property] > b[property] ? 1 : 0;
- return result * sortOrder;
- };
- };
- export const dateHelper = (date: string, hideTime?: boolean, shortMonth?: boolean) => {
- if (!date) {
- return '-';
- }
- const d = customDateConstructor(date);
- const newDate =
- d.getDate() + ' ' + (shortMonth ? MONTH_SHORT_NAME[d.getMonth()] : MONTH_NAME[d.getMonth()]) + ' ' + d.getFullYear();
- const newTime = zeroFormat(d.getHours()) + ':' + zeroFormat(d.getMinutes());
- return newDate + (hideTime ? '' : ' pukul ' + newTime);
- };
- // use this function if need to convert timezone by region in FE
- export const timezoneDateHelper = (date: string, region: IRegionData | any, hideTime?: boolean, shortMonth?: boolean, showDay?: boolean) => {
- if (!date) {
- return '-';
- }
- const d = customDateConstructor(date);
- const timeZone = region ? region.country_timezone : 'Asia/Jakarta';
- const locale = region ? region.default_locale_id : 'id-ID';
- const dayOptions: any = {
- timeZone: timeZone,
- weekday: 'long',
- };
- const dateOptions: any = {
- timeZone: timeZone,
- year: 'numeric',
- month: shortMonth == undefined ? 'long' : (shortMonth ? 'short' : 'long'),
- day: 'numeric',
- };
- const timeOptions: any = {
- timeZone: timeZone,
- hour: 'numeric',
- minute: 'numeric',
- };
- if (!region || region.country_code == REGION_CODE.INDONESIA) {
- return dateHelper(date, hideTime, shortMonth);
- } else {
- let options = { ...dateOptions };
- if (!hideTime) {
- options = { ...options, ...timeOptions };
- }
- if (showDay) {
- options = { ...options, ...dayOptions };
- }
- return d.toLocaleString(locale, options);
- }
- };
- export const customDateConstructor = (date: string) => {
- return isIos() || isSafari() ? convertDateForIos(date) : new Date(date);
- };
- export const detailedDateHelper = (date: string, hideTime?: boolean) => {
- const d = customDateConstructor(date);
- const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des'];
- const newDate = d.getDate() + ' ' + monthNames[d.getMonth()] + ' ' + d.getFullYear();
- const newTime =
- ' - ' + zeroFormat(d.getHours()) + ':' + zeroFormat(d.getMinutes()) + ':' + zeroFormat(d.getSeconds());
- return newDate + (hideTime ? '' : ' ' + newTime);
- };
- export function convertDateForIos(date: string) {
- const normalDate = new Date(date);
- if (isNaN(normalDate.getDate())) {
- const arr = date.split(/[- :]/);
- const intArray = arr.map((element) => parseInt(element));
- const parsedDate = new Date(intArray[0], intArray[1] - 1, intArray[2], intArray[3], intArray[4], intArray[5]);
- return parsedDate;
- } else {
- return normalDate;
- }
- }
- export const zeroFormat = (num: any) => {
- return num < 10 ? '0' + num : num;
- };
- export const objectSearch = (value: any, nameKey: any, myArray: any) => {
- for (let i = 0; i < myArray.length; i++) {
- if (myArray[i][nameKey] === value) {
- return i;
- }
- }
- return false;
- };
- export const inArray = (needle: number | string, haystack: any[]): boolean => {
- const length = haystack.length;
- for (let i = 0; i < length; i++) {
- if (haystack[i] === needle) {
- return true;
- }
- }
- return false;
- };
- export const isFile = (value: any, checkType?: string) => {
- return (
- value !== undefined &&
- value.name !== undefined &&
- value.size !== undefined &&
- (checkType === undefined || value.name.substring(value.name.lastIndexOf('.') + 1) === checkType)
- );
- };
- export const processCSV = (fileStream: string | ArrayBuffer | null) => {
- let csvObj: any = [];
- if (typeof fileStream === 'string') {
- csvObj = fileStream.split('\n');
- if (csvObj.length) {
- csvObj.forEach((el: string, idx: number) => {
- csvObj[idx] = el.split(',');
- });
- }
- }
- return csvObj;
- };
- export function isSupportWebp() {
- const isMac = osName === OsTypes.MAC_OS;
- const isApple = osName === OsTypes.IOS;
- if (isApple) {
- const isNewSafari = isSafari() && parseFloat(browserVersion) >= 14;
- return isNewSafari || isChrome;
- }
- if (isMac) {
- const isMacBigSur = parseFloat(osVersion) >= 11;
- const isNewSafari = browserName === BrowserTypes.Safari && parseFloat(browserVersion) >= 14;
- return isMacBigSur && isNewSafari;
- } else {
- return true;
- }
- }
- export function isNaNOrUndefinedHelper<T = number>(
- userIdNumber: number | undefined,
- defaultValue: T | null = null,
- ): T | number | null {
- return userIdNumber ? (isNaN(userIdNumber) ? defaultValue : userIdNumber) : defaultValue;
- }
- export const isImage = (extension?: string) => {
- const imageExtension = ['.webp', '.png', '.jpg', '.jpeg'];
- return extension && imageExtension.includes(extension);
- };
- export function newGenImage(url: string) {
- const isHttp = url?.slice(0, 4) === 'http';
- if (isHttp && url) {
- const urlExtension = url.split('.').pop();
- // because some image return like this
- const newUrl = isImage(`.${urlExtension}`) ? url?.replace(`.${urlExtension}`, '.webp') : url + '.webp';
- return newUrl;
- } else {
- return url;
- }
- }
- export const phoneFormatHelper = (phoneNumber: string, reverse?: boolean) => {
- if (phoneNumber) {
- if (reverse) {
- if (phoneNumber.substring(0, 3) === '628') {
- return '08' + phoneNumber.substring(3);
- }
- } else if (phoneNumber.substring(0, 2) === '08') {
- return '628' + phoneNumber.substring(2);
- }
- return phoneNumber;
- }
- return '';
- };
- export const phoneVisualFormatHelper = (phonenumber: string) => {
- phonenumber = phoneFormatHelper(phonenumber, true);
- return `${phonenumber.slice(0, 4)}-${phonenumber.slice(4, 8)}-${phonenumber.slice(8)}`;
- };
- export function isMobile() {
- return typeof window !== 'undefined' ? /(android|iphone|ipad|mobile)/i.test(navigator.userAgent) : false;
- }
- export function isIos() {
- return typeof window !== 'undefined'
- ? /iPad|iPhone|iPod|Mac/.test(navigator.platform) ||
- (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)
- : false;
- }
- export function isSafari() {
- return typeof window !== 'undefined' ? /^((?!chrome|android).)*safari/i.test(navigator.userAgent) : false;
- }
- export function getBlobUrlFromFile(file: File) {
- return URL.createObjectURL(file);
- }
- export async function blobUrlToFile(url: string, filename: string, mimeType: string) {
- const options = {
- type: mimeType,
- };
- return window
- .fetch(url)
- .then((res: any) => {
- return res.blob();
- })
- .then((blob: any) => {
- return new window.File([blob], filename, options);
- });
- }
- export function secondsToDayHourMinuteFormat(seconds: number, translation: ITranslation) {
- const days = Math.floor(seconds / (3600 * 24));
- const hour = Math.floor((seconds % (3600 * 24)) / 3600);
- const minute = Math.floor((seconds % 3600) / 60);
- const dayText = translateText('{{count}}_hari', translation.languageCode, translation.languageList, { count: days });
- const hourText = translateText('{{count}}_jam', translation.languageCode, translation.languageList, { count: hour });
- const minuteText = translateText('{{count}}_menit', translation.languageCode, translation.languageList, { count: minute });
- const dDisplay = days > 0 ? dayText + ' ' : '';
- const hDisplay = hour > 0 ? hourText + ' ' : '';
- const mDisplay = minute > 0 ? minuteText : '';
- return dDisplay + hDisplay + mDisplay;
- }
- export const localNumberUnitFormat = (inNumber: number, translation: ITranslation) => {
- const millionText = translateText('juta', translation.languageCode, translation.languageList);
- const billionText = translateText('milyar', translation.languageCode, translation.languageList);
- const trillionText = translateText('trilliun', translation.languageCode, translation.languageList);
- const unit = ['', millionText, billionText, trillionText];
- const unitAmount = [1, 1000000, 1000000000, 1000000000000];
- let biggestUnitIndex = -1;
- let numberByUnit = 0.0;
- for (let i = unit.length - 1; i >= 0; i--) {
- if (inNumber >= unitAmount[i]) {
- biggestUnitIndex = i;
- numberByUnit = inNumber / unitAmount[i];
- break;
- }
- }
- let unitString = '';
- if (biggestUnitIndex >= 0) {
- unitString = unit[biggestUnitIndex];
- if (unitString !== '') {
- unitString = ' ' + unitString;
- }
- }
- return numberByUnit + unitString;
- };
- // try to take from laravel https://github.com/laravel/framework/blob/9.x/src/Illuminate/Support/Str.php
- export function convertToSlug(str: string) {
- if (typeof str !== 'string') return str;
- return str
- .toLowerCase()
- // Convert all underscores into -
- .replace(/_/g, ' ')
- // Remove all characters that are not -, letters, numbers, or whitespace.
- .replace(/[^\w\s-]+/g, '')
- // Convert all white space into singgle space
- .replace(/\s+/g, ' ')
- .trim()
- // Convert all white space to -
- .replace(/ /g, '-');
- }
- export function stringToBoolean(str: string) {
- let bool;
- if (str === 'true') {
- bool = true;
- } else if (str === '1') {
- bool = true;
- } else {
- bool = false;
- }
- return bool;
- }
- export function arrayToSentence(arr: string[]) {
- if (arr.length === 0) return '';
- if (arr.length === 1) return arr[0];
- const strArr = [...arr];
- const last = strArr.pop();
- return strArr.join(', ') + ' dan ' + last;
- }
- export function isSlug(params: string) {
- return /^[\w\s-]+$/.test(params);
- }
- export function isAlphaNumericSpace(str: string) {
- return /^[\w\s]+$/.test(str);
- }
- export function isProductKeywordSafe(str: string) {
- return /^[\w\s-()|'.+,!\\/$]+$/.test(str);
- }
- export const stringToSlug = (input: string) => {
- input = input.replace(/^\s+|\s+$/g, ''); // trim
- input = input.toLowerCase();
- input = input
- .replace(/[^a-z0-9 -]/g, '')
- .replace(/\s+/g, '-')
- .replace(/-+/g, '-');
- return input;
- };
- export const getRandomNumber = (min: number, max: number) => {
- return Math.floor(Math.random() * (max - min) + min);
- };
- export function arrayObjectToArray(obj: Array<object>, index: string) {
- const temp: any = [];
- const objTemp: any = {};
- try {
- obj.forEach((data: any) => {
- temp.push(data[index]);
- objTemp[data[index]] = data;
- });
- return { temp, objTemp };
- } catch (e) {
- return { temp, objTemp };
- }
- }
- export function filterObjectUndefinedProp(data: any) {
- return Object.keys(data).reduce((acc: any, key: string) => {
- const value = data[key];
- return value === undefined || value === '' ? acc : { ...acc, [key]: data[key] };
- }, {});
- }
- export function addSpaceOn4thChar(value: any) {
- if (value) {
- value = value.replace(/\W/gi, '').replace(/(.{4})/g, '$1 ');
- value = value.trimEnd();
- return value;
- } else {
- return '';
- }
- }
- export function toCommaDelimiter(number: number) {
- return number.toString().split('.').join(',');
- }
- export function formatMilisecondsToTimeRemaining(duration: number) {
- if (duration < 0) return '00:00:00';
- const seconds = Math.floor((duration / 1000) % 60);
- const minutes = Math.floor((duration / (1000 * 60)) % 60);
- const hours = Math.floor((duration / (1000 * 60 * 60)) % 24);
- const strHours = hours < 10 ? '0' + hours : hours;
- const strMinutes = minutes < 10 ? '0' + minutes : minutes;
- const strSeconds = seconds < 10 ? '0' + seconds : seconds;
- return strHours + ':' + strMinutes + ':' + strSeconds;
- }
- export function numberToDayOfWeek(number: number) {
- if (number > 6 || number < 0) return '';
- const day = ['Minggu', 'Senin', 'Selasa', 'Rabu', 'Kamis', 'Jumat', 'Sabtu'];
- return day[number];
- }
- export function unixTimeToDayInNumber(date: string) {
- const dateTest = Date.parse(date);
- const today = new Date().getTime();
- const expireDay = Math.round((dateTest - today) / 86400000);
- return expireDay;
- }
- export function formatDayDateTimeWIB(date: Date) {
- const day = numberToDayOfWeek(date.getDay());
- const formattedDate = dateHelper(date.toString());
- return `${day}, ${formattedDate} WIB`;
- }
- // use this function if need to convert timezone by region in FE
- export function timezoneFormatDayDateTime(date: Date, region: IRegionData) {
- if (!region || region.country_code == REGION_CODE.INDONESIA) {
- const formattedDate = dateHelper(date.toString());
- const day = numberToDayOfWeek(date.getDay());
- return `${day}, ${formattedDate} WIB`;
- } else {
- return timezoneDateHelper(date.toString(), region, false, false, true);
- }
- }
- export function msToMinutes(ms: number) {
- return Math.floor(ms / 60000);
- }
- export function timeIsBetweenHours(time: Date, startHour: number, endHour: number, options?: { gmt?: number }) {
- let currMinutes = time.getHours() * 60 + time.getMinutes();
- if (options && options.gmt !== null && options.gmt !== undefined) {
- const offsetMins = time.getTimezoneOffset();
- const utcMinutes = currMinutes + offsetMins;
- currMinutes = utcMinutes + options.gmt * 60;
- }
- if (currMinutes < 0) currMinutes += 1440;
- if (currMinutes >= 1440) currMinutes -= 1440;
- const startMinutes = startHour * 60;
- const endMinutes = endHour * 60;
- return currMinutes > startMinutes && currMinutes < endMinutes;
- }
- export function isGmail(data: string) {
- const mailFormat = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
- if (data.match(mailFormat)) {
- const mailSplit = data.split('@');
- if (mailSplit[1].search(/gmail/) == 0) {
- return true;
- } else {
- return false;
- }
- } else {
- return false;
- }
- }
- export function arrayIntersects(array1: any[], array2: any[]) {
- if (array1) {
- return array1.some((item: any) => array2.includes(item));
- }
- }
- export function discountCalc(price: number, competitorPrice: number) {
- if (competitorPrice) {
- const value = Math.round(((competitorPrice - price) / competitorPrice) * 100);
- return value >= MIN_SHOWN_DISCOUNT_PERCENT ? value : 0;
- }
- return 0;
- }
- export function getWithdrawAmount(balance: number, topupLimit: number, options = { multiplier: 1000, minimum: 20000 }) {
- if (topupLimit >= balance) return 0;
- const difference = balance - topupLimit;
- if (difference < options.minimum) return options.minimum;
- const withdraw = Math.ceil(difference / options.multiplier) * options.multiplier;
- return withdraw;
- }
- export function getTopUpAmount(balance: number, totalPayment: number, options = { multiplier: 1000, minimum: 10000 }) {
- if (totalPayment <= balance) return 0;
- const difference = totalPayment - balance;
- if (difference < options.minimum) return options.minimum;
- const topup = Math.ceil(difference / options.multiplier) * options.multiplier;
- return topup;
- }
- export function getDayCountBetween(startDate: Date, endDate: Date) {
- const millisecondsPerDay = 24 * 60 * 60 * 1000;
- return (endDate.getTime() - startDate.getTime()) / millisecondsPerDay;
- }
- export const doCopy = (text: string) => {
- navigator.clipboard.writeText(text);
- };
- export const toPascalCase = (text: string | undefined) => {
- if (!text || typeof text !== 'string') return text;
- return text
- .replace(/(\w)(\w*)/g, (_g0, g1, g2) => {
- return g1.toUpperCase() + g2.toLowerCase();
- })
- .replace(/\s/g, '');
- };
- export const arrayObjectToArrayValue = (array: any[], valueName: string) => {
- return array.map((val: any) => {
- return val[valueName];
- });
- };
- export function durationHandler(startTime: string, endTime: string) {
- const startDate = customDateConstructor(startTime);
- const endData = customDateConstructor(endTime);
- const isSameMonth = startDate.getMonth() === endData.getMonth();
- const isSameYear = startDate.getFullYear() === endData.getFullYear();
- let startMounth = '';
- const startYear = isSameYear ? '' : `${startDate.getFullYear()} `;
- if (isSameYear) {
- startMounth = isSameMonth ? '' : MONTH_NAME[startDate.getMonth()] + ' ';
- } else {
- startMounth = MONTH_NAME[startDate.getMonth()] + ' ';
- }
- const initalString = `${startDate.getDate()} ${startMounth}${startYear}`;
- return `${initalString} - ${dateHelper(endTime, true)}`;
- }
- export function addDurationDate(date: string, duration: number, region: IRegionData) {
- date = date.replace(/ /g, 'T');
- const endDate = new Date(date);
- endDate.setDate(endDate.getDate() + duration);
- const customEndDate = customDateConstructor(endDate.toString());
- return timezoneDateHelper(customEndDate.toString(), region, false, false, false);
- }
- export async function copyText(text: string) {
- if (typeof text !== 'string') return;
- const fallbackCopy = () => {
- try {
- copy(text);
- } catch (error) {
- // Give up trying to copy
- throw Error(error as any);
- }
- };
- // New clipboard API for modern browser
- if (navigator?.clipboard?.writeText) {
- try {
- await navigator.clipboard.writeText(text);
- } catch (error) {
- fallbackCopy();
- }
- } else {
- // Fallback for old browser, update if document.execCommand('copy') is not longer supported.
- fallbackCopy();
- }
- }
- export const stringBuilder = (text: string, params: Record<string, string>) => {
- let tempText = text;
- Object.keys(params).forEach((key) => {
- tempText = tempText.replace(`{${key}}`, params[key]);
- });
- return tempText;
- };
- export const getMsDifferenceBetweenDates = (
- startDate: Date,
- endDate: Date,
- options?: { startDateGmt?: number; endDateGmt?: number },
- ) => {
- const minutesToMs = 60000;
- let startTime = startDate.getTime();
- if (options && options.startDateGmt !== null && options.startDateGmt !== undefined) {
- const offsetTime = startDate.getTimezoneOffset() * minutesToMs;
- const utcTime = startTime + offsetTime;
- startTime = utcTime + options.startDateGmt * 60 * minutesToMs;
- }
- let endTime = endDate.getTime();
- if (options && options.endDateGmt !== null && options.endDateGmt !== undefined) {
- const offsetTime = endDate.getTimezoneOffset() * minutesToMs;
- const utcTime = endTime + offsetTime;
- endTime = utcTime + options.endDateGmt * 60 * minutesToMs;
- }
- return endTime - startTime;
- };
- export const stringToArrayNumber = (string: string) => {
- if (string) {
- return string.slice(1, -1).split(',').map(Number);
- }
- return [];
- };
- export const sleep = (ms: number) => {
- return new Promise((resolve) => setTimeout(resolve, ms));
- };
- export const removeUndefinedValue = (value: { [key: string]: any }) => {
- const newObjectValue = { ...value };
- Object.keys(newObjectValue).forEach((key: any) => {
- if (newObjectValue[key] === null || newObjectValue[key] === undefined) {
- delete newObjectValue[key];
- }
- });
- return newObjectValue;
- };
- export const replaceUndefinedPropsToNull = <T>(object: { [key: string]: any }) => {
- if (!object || typeof object !== 'object') return object;
- for (const key in object) {
- if (object[key] === undefined) object[key] = null;
- }
- return object as T;
- };
- export const parseStringArray = <T>(str: string) => {
- try {
- const result = JSON.parse(str);
- if (!Array.isArray(result)) return [];
- return result as T[];
- } catch {
- return [] as T[];
- }
- };
- export const isProduction = () => {
- return config.environment === 'production';
- };
- export const isDevelopment = () => {
- return config.environment === 'development' || config.environment === 'local';
- };
- export const capitalizeFirstLetter = (str: string) => {
- if (!str || typeof str !== 'string') return str;
- return str.charAt(0).toUpperCase() + str.slice(1);
- };
- export const isNotificationAPISupported = (): boolean => (typeof window !== 'undefined') && ('Notification' in window);
- export const replaceAll = (text: string, key: string, replace: string) => {
- return text.replace(new RegExp(key, 'g'), replace);
- };
- export const exchangeRateConversionHelper = (foreignExchangeRate: IForeignExchangeRate | any, region: IRegionData | any, amount: number | null): number => {
- if (!amount || !foreignExchangeRate) { return 0; }
- if ((region.country_code == REGION_CODE.INDONESIA) || foreignExchangeRate.source_currency == 'IDR' && foreignExchangeRate.target_currency == 'IDR') {
- return amount;
- }
- const locale = region ? region.default_locale_id : 'id-ID';
- // eslint-disable-next-line @babel/new-cap
- const formater = Intl.NumberFormat(locale, {
- maximumFractionDigits: 2,
- });
- return parseFloat(formater.format((amount / foreignExchangeRate.exchange_rate)));
- };
- export const currencyHelper = (foreignExchangeRate: IForeignExchangeRate | any, region: IRegionData | any, amount: number | null, isConverted: boolean = false): string => {
- if (amount == null || amount == undefined || !foreignExchangeRate) { return ''; }
- if (amount <= 0) { amount = 0; }
- if ((region.country_code == REGION_CODE.INDONESIA) || foreignExchangeRate.source_currency == 'IDR' && foreignExchangeRate.target_currency == 'IDR') {
- return `Rp${moneyDot(amount)}`;
- }
- const locale = region ? region.default_locale_id : 'id-ID';
- let convertedAmounts = amount / foreignExchangeRate.exchange_rate;
- let truncVal = Math.trunc(convertedAmounts * 1000) / 1000;
- let roundedVal = Math.round((truncVal + Number.EPSILON) * 100) / 100;
- let result = (isConverted ? amount : roundedVal).toLocaleString(locale, { style: 'currency', currency: foreignExchangeRate.source_currency, maximumFractionDigits: 2 });
- return result;
- };
Advertisement
Add Comment
Please, Sign In to add comment