Last active
January 27, 2022 12:21
-
-
Save dilipsuthar97/8a61a2390e428f885a0b8cc9a07551ae to your computer and use it in GitHub Desktop.
Global helper functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Constants } from '../CommonConfig'; | |
import moment from 'moment'; | |
/** | |
* Return random number between inclusive and exclusive | |
* @param {Number} length - exclusive length for randome number | |
* @param {Boolean} countOne - add plus 1 count | |
*/ | |
const getRandomNumber = (exclusiveLength = 1, countOne = false) => { | |
if (countOne) { | |
return Math.floor(Math.random() * exclusiveLength + 1); | |
} else { | |
return Math.floor(Math.random() * exclusiveLength); | |
} | |
}; | |
/** | |
* Return a random UUID identifier (always generates random UUID ) | |
*/ | |
const getUUID = () => { | |
var dt = new Date().getTime(); | |
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace( | |
/[xy]/g, | |
function (c) { | |
var r = (dt + Math.random() * 16) % 16 | 0; | |
dt = Math.floor(dt / 16); | |
return (c == 'x' ? r : (r & 0x3) | 0x8).toString(16); | |
}, | |
); | |
return uuid; | |
}; | |
/** | |
* Return a trimmed string by removing extra spaces | |
* @param {String} text - message to be trimmed | |
*/ | |
const trimString = (text) => { | |
if (typeof text == 'string') { | |
return text.replace(/\s+/g, ' ').trim(); | |
} | |
return text; | |
}; | |
/** | |
* Returns an array with arrays of the given size | |
* | |
* @param {Array} myArray - data array to split | |
* @param {Number} chunkSize - size of every group | |
*/ | |
const chunkArray = (myArray, chunkSize) => { | |
var index = 0; | |
var arrayLength = myArray.length; | |
var tempArray = []; | |
for (index = 0; index < arrayLength; index += chunkSize) { | |
// Do something if you want with the group | |
tempArray.push(myArray.slice(index, index + chunkSize)); | |
} | |
return tempArray; | |
}; | |
const getHitSlop = (hitSlop = 5) => { | |
return { | |
top: hitSlop, | |
bottom: hitSlop, | |
right: hitSlop, | |
left: hitSlop, | |
}; | |
}; | |
/** | |
* Format the given time into 00:00 | |
* @param {Number} seconds - value to test | |
*/ | |
const formatTime = (secs) => { | |
let minutes = Math.floor(secs / 60); | |
let seconds = Math.ceil(secs - minutes * 60); | |
if (seconds < 10) seconds = `0${seconds}`; | |
return `${minutes}:${seconds}`; | |
}; | |
/** | |
* Return formatted timestamp string for event | |
* @param {String} startTimestamp | |
* @param {String} endTimestamp | |
* @param {Object} options | |
*/ | |
const getEventTimestamp = ( | |
startTimestamp, | |
endTimestamp, | |
{ type = 'event', checkSameDay = false, checkDayType = true } = {}, | |
) => { | |
const getday = (date) => { | |
return checkDayType | |
? moment(date).calendar(null, { | |
lastDay: '[Yesterday]', | |
sameDay: '[Today]', | |
nextDay: '[Tomorrow]', | |
lastWeek: 'ddd, DD MMM', | |
nextWeek: 'ddd, DD MMM', | |
sameElse: 'ddd, DD MMM', | |
}) | |
: moment(date).format('ddd, DD MMM'); | |
}; | |
if (type == 'post') { | |
return moment(startTimestamp) | |
.format('MMM DD, h:mma') | |
.concat(' - ') | |
.concat(moment(endTimestamp).format('MMM DD, h:mma [UTC]Z')); | |
} | |
var x = moment(startTimestamp).format('YYYY-MM-DD'); | |
var y = moment(endTimestamp).format('YYYY-MM-DD'); | |
var isTimeSame = x == y; | |
let formattedDate = ''; | |
if (startTimestamp) { | |
const time = moment(startTimestamp).format( | |
`[at] hh:mm a${!endTimestamp ? ' [UTC]Z' : ''}`, | |
); | |
const day = getday(startTimestamp); | |
formattedDate = day + ' ' + time; | |
} | |
if (endTimestamp) { | |
var time = ''; | |
if (checkSameDay && isTimeSame) { | |
time = moment(endTimestamp).format('hh:mm a [UTC]Z'); | |
formattedDate += ' - ' + time; | |
} else { | |
time = moment(endTimestamp).format('[at] hh:mm a [UTC]Z'); | |
const day = getday(endTimestamp); | |
formattedDate += ' - ' + day + ' ' + time; | |
} | |
} | |
return formattedDate; | |
}; | |
/** | |
* Return formatted string for long numbers | |
* @param {Number} n - Long number | |
*/ | |
const formatLongNumbers = (n) => { | |
if (n < 1e3) return String(n).length > 1 ? n : n.pad(2); | |
if (n >= 1e3 && n < 1e6) return +(n / 1e3).toFixed(1) + 'K'; | |
if (n >= 1e6 && n < 1e9) return +(n / 1e6).toFixed(1) + 'M'; | |
if (n >= 1e9 && n < 1e12) return +(n / 1e9).toFixed(1) + 'B'; | |
if (n >= 1e12) return +(n / 1e12).toFixed(1) + 'T'; | |
}; | |
/** | |
* Return formatted amount value with $ sign | |
* @param {String} n - amount value | |
*/ | |
const formatPrice = (amount) => { | |
return '$ '.concat(amount.toFixed(0).replace(/\d(?=(\d{3})+\.)/g, '$&,')); | |
}; | |
const isVideo = (mediaObjUrl) => { | |
return ( | |
['flv', 'mp4', 'm3u8', 'ts', '3gp', 'mov', 'avi', 'wmv'].indexOf( | |
mediaObjUrl?.split('.')?.pop() ?? '', | |
) > -1 | |
); | |
}; | |
const videoExt = () => { | |
return ['flv', 'mp4', 'm3u8', 'ts', '3gp', 'mov', 'avi', 'wmv']; | |
}; | |
const isMusic = (mediaObjUrl) => { | |
return ( | |
[ | |
'aif', | |
'aiff', | |
'au', | |
'flac', | |
'mp3', | |
'snd', | |
'wav', | |
'w64', | |
'mpeg', | |
'ogg', | |
].indexOf(mediaObjUrl?.split('.')?.pop() ?? '') > -1 | |
); | |
}; | |
const formatBytes = (bytes) => { | |
return bytes / (1024 * 1024); | |
}; | |
const fromNow = (date) => { | |
var now = moment().format('DD/MM/YYYY HH:mm:ss'); | |
var then = moment(date).format('DD/MM/YYYY HH:mm:ss'); | |
var ms = moment.utc( | |
moment(now, 'DD/MM/YYYY HH:mm:ss').diff( | |
moment(then, 'DD/MM/YYYY HH:mm:ss'), | |
), | |
); | |
var d = moment.duration(ms); | |
if (d?._data?.days > 7 || d?._data?.months >= 1 || d?._data?.years >= 1) { | |
return moment(date).format('DD MMMM YYYY'); | |
} else if (d?._data?.days >= 1 && d?._data?.days <= 7) { | |
return d?._data?.days + ` ${d?._data?.days > 1 ? 'days' : 'day'} ago`; | |
} else if (d?._data?.hours >= 1 && d?._data?.hours <= 23) { | |
return ( | |
d?._data?.hours + ` ${d?._data?.hours > 1 ? 'hours' : 'hour'} ago` | |
); | |
} else if (d?._data?.minutes >= 1 && d?._data?.minutes <= 59) { | |
return ( | |
d?._data?.minutes + | |
` ${d?._data?.minutes > 1 ? 'minutes' : 'minute'} ago` | |
); | |
} else if (d?._data?.seconds >= 1 && d?._data?.seconds <= 59) { | |
return ( | |
d?._data?.seconds + | |
` ${d?._data?.seconds > 1 ? 'seconds' : 'second'} ago` | |
); | |
} else { | |
return moment(date).format('DD MMMM YYYY'); | |
} | |
}; | |
const isUrlValid = (url) => { | |
var res = url.match( | |
/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g, | |
); | |
if (res == null) return false; | |
else return true; | |
}; | |
const createSocialLink = (userName, type) => { | |
switch (type) { | |
case 1: // facebook | |
return `https://www.facebook.com/${userName ?? ''}`; | |
case 2: // twitter | |
return `https://www.twitter.com/${userName ?? ''}`; | |
case 3: // youtube | |
return `https://youtube.com/c/${userName ?? ''}`; | |
case 4: // instagram | |
return `https://www.instagram.com/${userName ?? ''}`; | |
} | |
}; | |
/** | |
* From list of elements of an array to new postions | |
* @param {Array} arr | |
* @param {Array} fromIndex | |
* @param {Array} toIndex | |
* @returns | |
*/ | |
const moveElements = (arr = [], fromIndex = [], toIndex = []) => { | |
const temp = Array.from(arr); | |
fromIndex.forEach((val, index) => { | |
var element = temp[val]; | |
temp.splice(val, 1); | |
temp.splice(toIndex[index], 0, element); | |
}); | |
return temp; | |
}; | |
/** | |
* Find the all index position of element in array which satify the condition | |
* @param {Array} arr | |
* @param {function} condition | |
* @returns | |
*/ | |
const findPositions = ( | |
arr = [], | |
predicate = (value, index) => false, | |
skipFirst = false, | |
) => { | |
const temp = []; | |
arr.forEach((value, index) => { | |
if (predicate(value, index) && !(skipFirst && index == 0)) { | |
temp.push(index); | |
} | |
}); | |
return temp; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment