import electron from 'electron'; import path from 'path'; import fs from 'fs-extra'; import { IObject } from '../types/common'; export const randomString = ( n: number, possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', ): string => { let text = ''; for (let i = 0; i < n; i += 1) { text += possible.charAt(Math.floor(Math.random() * possible.length)); } return text; }; export const randomNumber = (min: number, max: number): number => { return Math.round(Math.random() * (max - min)) + min; }; export const randomIndexFromArray = (arr: any[]): any => { return Math.floor(Math.random() * arr.length); }; export const randomValueFromArray = (arr: any[]): any => { return arr[randomIndexFromArray(arr)]; }; export const removeObjectKey = (obj: IObject, prop: string | number): IObject => { const { [prop]: omit, ...res } = obj; return res; }; export const removeObjectKeys = ( obj: IObject, props: Array = [], ): IObject => { let object = obj; for (let i = 0; i < props.length; i += 1) { const prop = props[i]; object = removeObjectKey(object, prop); } return object; }; export const escapeRegExp = (str: string): string => (str || '').replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); export const validUrl = (str: string) => { return /^https?:\/\/.+/.test(str); }; export const validEmail = (email: string): boolean => { // eslint-disable-next-line no-useless-escape const re = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i; return re.test(email); }; export const getDateFromString = (dateString: string): null | Date => { if (new RegExp('^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$', 'im').test(dateString)) { const d = new Date(dateString); if (d.toString() !== 'Invalid Date') { return d; } } return null; }; export const convertStringToNumber = (str: string | null | number): number | null => { const convertedStr = `${str}`.replace(/,/g, '').trim(); if (/^[-+]?[0-9]+(?:\.[0-9]+)?$/.test(convertedStr)) { return parseFloat(convertedStr); } return null; }; export const sleep = (ms: number): Promise => { return new Promise((resolve) => { setTimeout(() => { resolve(); }, ms); }); }; export const getAppFolder = (): string => { const userDataPath = (electron.app || electron.remote.app).getPath('userData'); const dbPath = path.join(userDataPath, electron.app.name); fs.ensureDirSync(dbPath); return dbPath; };