You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
58 lines
1.6 KiB
58 lines
1.6 KiB
2 years ago
|
// General helper functions
|
||
|
|
||
|
export const cancelablePromise = promise => {
|
||
|
let isCanceled = false
|
||
|
|
||
|
const wrappedPromise = new Promise((resolve, reject) => {
|
||
|
promise.then(
|
||
|
value => (isCanceled ? reject({ isCanceled, value }) : resolve(value)),
|
||
|
error => reject({ isCanceled, error })
|
||
|
)
|
||
|
})
|
||
|
|
||
|
return {
|
||
|
promise: wrappedPromise,
|
||
|
cancel: () => (isCanceled = true),
|
||
|
}
|
||
|
}
|
||
|
|
||
|
export const noop = () => {}
|
||
|
|
||
|
export const delay = (n = 550) => new Promise(resolve => setTimeout(resolve, n))
|
||
|
|
||
|
export const isObject = obj => { return Object.prototype.toString.call(obj) === '[object Object]' }
|
||
|
|
||
|
export const convertToDuration = (milliseconds) => {
|
||
|
const stringifyTime = (time) => String(time).padStart(2, '0')
|
||
|
const seconds = Math.floor(milliseconds / 1000)
|
||
|
const minutes = Math.floor(seconds / 60)
|
||
|
const hours = Math.floor(minutes / 60)
|
||
|
return `${stringifyTime(hours)}:${stringifyTime(
|
||
|
minutes % 60
|
||
|
)}:${stringifyTime(seconds % 60)}`
|
||
|
}
|
||
|
|
||
|
export const convertToTimeWorked = (milliseconds) => {
|
||
|
const seconds = Math.floor(milliseconds / 1000)
|
||
|
const minutes = Math.floor(seconds / 60)
|
||
|
const hours = Math.floor(minutes / 60)
|
||
|
|
||
|
if (hours > 0) {
|
||
|
return `${hours}h, ${minutes % 60}m`
|
||
|
} else {
|
||
|
return `${minutes % 60}m`
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// Returns a random int between min and max (inclusive)
|
||
|
export function randomInt(min, max) {
|
||
|
min = Math.ceil(min);
|
||
|
max = Math.floor(max);
|
||
|
return Math.floor(Math.random() * (max - min + 1)) + min;
|
||
|
}
|
||
|
|
||
|
// Returns a random item from the given array
|
||
|
export function selectRandom(arrayToChooseFrom) {
|
||
|
return arrayToChooseFrom[randomInt(0, arrayToChooseFrom.length - 1)]
|
||
|
}
|