In this article, I will share with you some JavaScript Functions that I almost use in every single project.
Check Them in GitHub
randomNumber();
Generates a random number between min and max numbers.
/**
* Generating random integers between min and max.
* @param {number} min Min number
* @param {number} max Max Number
*/
export const randomNumber = (min = 0, max = 1000) =>
Math.ceil(min + Math.random() * (max - min));
// Example
console.log(randomNumber()); // 97
capitalize();
Making the first letter of a string to Uppercase.
/**
* Capitalize Strings.
* @param {string} s String that will be Capitalized
*/
export const capitalize = (s) => {
if (typeof s !== "string") return "";
return s.charAt(0).toUpperCase() + s.slice(1);
};
// Example
console.log(capitalize("cat")); // Cat
truncate();
Usually used in combination with Tooltips.
/**
* Truncating a string...
* @param {string} text String to be truncated
* @param {number} num Max length of the `String` that will be truncated after
*/
export const truncate = (text, num = 10) => {
if (text.length > num) {
return `${text.substring(0, num - 3)}...`;
}
return text;
};
// Example
console.log(truncate("this is some long string to be truncated")); // this is...
toTop();
You can remove the behavior
property for instant scrolling to the top.
/**
* Scroll to top
*/
export const toTop = () => {
window.scroll({ top: 0, left: 0, behavior: "smooth" });
};
softDeepClone();
Deeply clone even nested
arrays or objects.
This function doesn't work with data types like
new Date()
,NaN
,undefined
,function
,Number
,Infinity
.
If you want to deep clone the mentioned data type you can use lodashcloneDeep();
function.
/**
* Deep cloning inputs
* @param {any} input Input
*/
export const softDeepClone = (input) => JSON.parse(JSON.stringify(input));
appendURLParams(); & getURLParams();
Append and get query strings, (Usually used with pagination).
/**
* Appen query string and return the value in a query string format.
* @param {string} key
* @param {string} value
*/
export const appendURLParams = (paramName, value) => {
const searchParams = new URLSearchParams(window.location.search);
searchParams.set(paramName, value);
return searchParams.toString();
};
// example
console.log(appendURLParams("name", "youssef")); // name=youssef
/**
* Get param name from URL.
* @param {string} name
*/
export const getURLParams = (name) =>
new URLSearchParams(window.location.search).get(name);
// Example
console.log(getURLParams(id)); // 5
getInnerHTML();
Getting inner text inside a stringed
HTML.
/**
* Getting the inner `Text` of an `HTML` string
* @param {string} str A string of HTML
*/
export const getInnerHTML = (str) => str.replace(/(<([^>]+)>)/gi, "");
toggleStrNum();
Usually used to deal with the server that sends and accepts string numbers.
/**
* returning "1" from "0" and the opposit.
* @param {string} strNum String Number ex: "0", "1"
*/
export const toggleStrNum = (strNum) => (strNum === "0" ? "1" : "0");
scrollToHide();
Scroll up to show the HTML element and down to hide it.
/**
* Hide HTML element when scrolling down.
* @param {string} id the `id` of an `HTML` element
* @param {string} distance in px ex: "100px"
*/
export const scrollToHide = (id, distance) => {
let prevScrollpos = window.pageYOffset;
window.onscroll = () => {
const currentScrollPos = window.pageYOffset;
if (prevScrollpos > currentScrollPos) {
document.getElementById(id).style.transform = `translateY(${distance})`;
} else {
document.getElementById(id).style.transform = `translateY(-${distance})`;
}
prevScrollpos = currentScrollPos;
};
};
humanFileSize ();
Converts the file size in Bytes
, and Returns the result in a Human Readable formate.
/**
* Converting Bytes to Readable Human File Sizes.
* @param {number} bytes Bytes in Number
*/
export const humanFileSize = (bytes) => {
let BYTES = bytes;
const thresh = 1024;
if (Math.abs(BYTES) < thresh) {
return `${BYTES} B`;
}
const units = ["kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
let u = -1;
const r = 10 ** 1;
do {
BYTES /= thresh;
u += 1;
} while (
Math.round(Math.abs(BYTES) * r) / r >= thresh &&
u < units.length - 1
);
return `${BYTES.toFixed(1)} ${units[u]}`;
};
// Example
console.log(humanFileSize(456465465)); // 456.5 MB
getTimes();
Returns times of the day every n
Minutes?
/**
* Getting an Array of Times + "AM" or "PM".
* @param {number} minutesInterval
* @param {number} startTime
*/
export const getTimes = (minutesInterval = 15, startTime = 60) => {
const times = []; // time array
const x = minutesInterval; // minutes interval
let tt = startTime; // start time
const ap = ["AM", "PM"]; // AM-PM
// loop to increment the time and push results in array
for (let i = 0; tt < 24 * 60; i += 1) {
const hh = Math.floor(tt / 60); // getting hours of day in 0-24 format
const mm = tt % 60; // getting minutes of the hour in 0-55 format
times[i] = `${`${hh === 12 ? 12 : hh % 12}`.slice(-2)}:${`0${mm}`.slice(
-2
)} ${ap[Math.floor(hh / 12)]}`; // pushing data in array in [00:00 - 12:00 AM/PM format]
tt += x;
}
return times;
};
// Example
console.log(getTimes());
/* [
"1:00 AM",
"1:15 AM",
"1:30 AM",
"1:45 AM",
"2:00 AM",
"2:15 AM",
"2:30 AM",
// ....
]
*/
setLocalItem(); & getLocalItem();
Caching data in LocalStorage
with expiry date.
/**
* Caching values with expiry date to the LocalHost.
* @param {string} key Local Storage Key
* @param {any} value Local Storage Value
* @param {number} ttl Time to live (Expiry Date in MS)
*/
export const setLocalItem = (key, value, ttl = duration.month) => {
const now = new Date();
// `item` is an object which contains the original value
// as well as the time when it's supposed to expire
const item = {
value,
expiry: now.getTime() + ttl,
};
localStorage.setItem(key, JSON.stringify(item));
};
/**
* Getting values with expiry date from LocalHost that stored with `setLocalItem`.
* @param {string} key Local Storage Key
*/
export const getLocalItem = (key) => {
const itemStr = localStorage.getItem(key);
// if the item doesn't exist, return null
if (!itemStr) {
return null;
}
const item = JSON.parse(itemStr);
const now = new Date();
// compare the expiry time of the item with the current time
if (now.getTime() > item.expiry) {
// If the item is expired, delete the item from storage
// and return null
localStorage.removeItem(key);
return null;
}
return item.value;
};
logFormattedStrings();
Logs any input in a human friendly string to the console.
/**
* Logging formatted strings
* @param {any} input
*/
export const logFormattedStrings = (input) =>
console.log(JSON.stringify(input, null, 4));
// Example
logFormattedStrings({ fName: "Youssef", lName: "Zidan" });
/*
{
"fName": "Youssef",
"lName": "Zidan"
}
*/
formatNumber();
/**
* Format numbers with separators.
* @param {number} num
*/
export const formatNumber = (num) => num.toLocaleString();
// Example
console.log(formatNumber(78899985)); // 78,899,985
You can also add other options to get other number formats such as currency, distance, weights, etc...
more details HERE
And here are two examples
export const toEGPCurrency = (num) =>
num.toLocaleString("ar-EG", { style: "currency", currency: "EGP" });
export const toUSDCurrency = (num) =>
num.toLocaleString("en-US", { style: "currency", currency: "USD" });
console.log(toUSDCurrency(78899985)); // $78,899,985.00
console.log(toEGPCurrency(78899985)); // ٧٨٬٨٩٩٬٩٨٥٫٠٠ ج.م.
toFormData();
/**
* Convert Objects to Form Data Format.
* @param {object} obj
*/
export const toFormData = (obj) => {
const formBody = new FormData();
Object.keys(obj).forEach((key) => {
if (Array.isArray(obj[key])) {
obj[key].forEach((val, i) => {
formBody.append(`${key}[${i}]`, val);
});
} else formBody.append(key, obj[key]);
});
return formBody;
};
getScreenWidth();
Retuns a string representing the width of the screen.
/**
* Detect screen width and returns a string representing the width of the screen.
*/
export const getScreenWidth = () => {
const screenWidth = window.screen.width;
if (screenWidth <= 425) return "mobile";
if (screenWidth <= 768) return "tablet";
if (screenWidth <= 1024) return "laptopSm";
if (screenWidth <= 1440) return "laptopLg";
if (screenWidth <= 2560) return "HD";
return screenWidth;
};
containsAll();
Check that every element in an array exsists in the another array.
/**
* Check that every element in an array exsists in the another array.
* @param {array} baseArr The array to make sure it has all the values
* @param {arr} arr The other array that will be compared with
*/
export const containsAll = (baseArr, arr) => {
let all = false;
for (let i = 0; i < arr.length; i += 1) {
if (baseArr.includes(arr[i])) {
all = true;
} else {
all = false;
return all;
}
}
return all;
};
getUniqueObjs();
Returns a unique array of objects based on a key
/**
* Returns a unique array of objects based on a key
* @param {array} array Array of objects
*/
export const getUniqueObjs = (array, key = "id") => {
const ids = [];
const output = [];
array.forEach((ele) => {
if (!ids.includes(ele[key])) {
ids.push(ele[key]);
output.push(ele);
}
});
return output;
};
Discussion (28)
for deep clone I prefer lodash because this method while it can be good in some cases it can fail.
Because it can lose data in some cases
Like Dates, functions, undefined, Infinity, RegExps, Maps, Sets, Blobs, or other complex types within your object it can be list or strigified
Its only good for object with string and numbers most of the time.
Still those are great functions that can be used in a large amount of projects
Thanks, My friend!
I modified the article based on your feedback!
there is a method I use a lot when I need to submit urls
Excellent!
Hello, nice list!
runEvery
function is broken, it runs a script every x milliseconds ifhour
is after the given hour andminute
is after the given minute, so given this input:and the time now is 3:17 PM it will try running at 8:17 PM but
now.getMinutes() >= mins
will return false and the function will not execute, and every 5 hours it will always return falseBut if you set minutes to 0 or someone starts the application after the provided minute it will execute every interval after the given time.
If the goal is to make a function that runs every day at a certain time, you need to get the time to the next occurrence and start the interval then, something like this:
Great!
Thanks for your feedback!
I'll check my code again and get back to you.
Hello!
I tried to run your function but it doesn't seem to be working.
Hey Youssif, I've just tried running the code in the console and it seems to be working.
You just need to set the time to be coming up in a minute or two so that you wouldn't wait for long for the next occurrence
and this one I am using regularly
Nice!
I like it!
i think it would be good for you to create this into an npm package.
It's on my plan but i need to increase the number of functions.
I would like to help with the npm
I would like to help too. Maybe we can build something bigger between us!
I have a bunch of react-native utils that may be interesting.
That's great!
Maybe we can do something together.
The way you're deep cloning is bad practice. If you're gonna copy and paste helpers might as ok copy and paste lodash's implementation.
Thanks, My friend!
I modified the article based on your feedback!
1024 = 1k bytes
Thanks, My friend!
I modified the article based on your feedback!
Nice collection, thanks!
Dear YoussefZidan,may I translate your article into Chinese?I would like to share it with more developers in China. I will give the original author and original source.
Sure!
Great Post!
I use Number.prototype.toLocaleString() to get formatted numbers 😁
This is amazing!
Thanks for sharing!
I Modified the article based on your feedback!
Thanks, my friend!
Thanks for sharing. I recommend you to create a Github gist for most of it and share the links here.
Thanks, Sure I'll do so.
That function where you try to parse HTML with regex doesn’t feel safe. You can't parse [X]HTML with regex. Because HTML can't be parsed by regex. Regex is not a tool that can be used to correctly parse HTML. As I have answered in HTML-and-regex questions here so many times before, the use of regex will not allow you to consume HTML. Regular expressions are a tool that is insufficiently sophisticated to understand the constructs employed by HTML. HTML is not a regular language and hence cannot be parsed by regular expressions. Regex queries are not equipped to break down HTML into its meaningful parts. so many times but it is not getting to me. Even enhanced irregular regular expressions as used by Perl are not up to the task of parsing HTML. You will never make me crack. HTML is a language of sufficient complexity that it cannot be parsed by regular expressions. Even Jon Skeet cannot parse HTML using regular expressions. Every time you attempt to parse HTML with regular expressions, the unholy child weeps the blood of virgins, and Russian hackers pwn your webapp. Parsing HTML with regex summons tainted souls into the realm of the living. HTML and regex go together like love, marriage, and ritual infanticide. The