Skip to content

Instantly share code, notes, and snippets.

View Ref-Bit's full-sized avatar
🔭
Learning...

Refaat Bitar Ref-Bit

🔭
Learning...
View GitHub Profile
@Ref-Bit
Ref-Bit / addDays
Created October 18, 2022 13:09
Add days to date object
const addDays = (date, days) => {
const result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
@Ref-Bit
Ref-Bit / asyncSleep
Created September 13, 2022 14:01
Add custom delay to asynchronous calls
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
@Ref-Bit
Ref-Bit / convertHHMMSSToSeconds
Created September 26, 2021 14:31
Convert time string format "hh:mm:ss" or "mm:ss" or "ss" to seconds
const convertHHMMSSToSeconds = timeStr => {
let p = timeStr.split(':'),
s = 0,
m = 1;
while (p.length > 0) {
s += m * parseInt(p.pop(), 10);
m *= 60;
}
@Ref-Bit
Ref-Bit / toBasicToken
Created June 17, 2021 11:31
Convert authentication info (username, password) to Basic token in NodeJS
const token = 'Basic ' + Buffer.from(`${username}:${password}`, 'utf8').toString('base64');
@Ref-Bit
Ref-Bit / removeObjKeys
Created December 31, 2020 12:25
Remove a property without mutating the object
const car = {
color: 'blue',
brand: 'Ford'
}
const prop = 'color';
const newCar = Object.keys(car).reduce((object, key) => {
if (key !== prop) {
object[key] = car[key]
}
@Ref-Bit
Ref-Bit / onlyUnique
Created December 30, 2020 09:18
Get all unique values in a JavaScript array (remove duplicates)
const onlyUnique = (value, index, self) => self.indexOf(value) === index;
@Ref-Bit
Ref-Bit / formatBytes
Created December 20, 2020 15:39
Convert Bytes number into (KB, MB, GB, TB,...) depending on its size.
const formatBytes = (bytes, decimals = 2) => {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
const convertFileToBlob = file => return URL.createObjectURL(file);
@Ref-Bit
Ref-Bit / convertFileToBase64
Created December 10, 2020 11:38
This is a function to convert file to base64 upon upload
const convertFileToBase64 = file =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
@Ref-Bit
Ref-Bit / anotherConvertFloatToHHMMSS
Last active December 9, 2020 07:29
This is a helper function to convert a float number to time format "hh:mm:ss".
const anotherConvertFloatToHHMMSS = secs => new Date(secs * 1000).toISOString().substr(11, 8);