DEV Community

Cover image for JavaScript Functions That Will Make Your Life Much Easier [Updatable].

JavaScript Functions That Will Make Your Life Much Easier [Updatable].

Youssef Zidan on January 30, 2021

Description Installation Usage Strings capitalize() truncate() toggleStrNum() camelCaseToSpaces() logFormattedStrings() getInnerHTML() random...
Collapse
 
talorlanczyk profile image
TalOrlanczyk

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

Collapse
 
youssefzidan profile image
Youssef Zidan • Edited

Thanks, My friend!
I modified the article based on your feedback!

Collapse
 
talorlanczyk profile image
TalOrlanczyk

there is a method I use a lot when I need to submit urls

export const isUrl = (s) => {
  // eslint-disable-next-line
  var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
  return regexp.test(s);
};
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
youssefzidan profile image
Youssef Zidan

Excellent!

Collapse
 
krimfandango profile image
Kareem Kamal • Edited

Hello, nice list!

runEvery function is broken, it runs a script every x milliseconds if hour is after the given hour and minute is after the given minute, so given this input:

runEvery(() => console.log('ran'), 12, 30, 300000)
Enter fullscreen mode Exit fullscreen mode

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 false
But 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:

function runEverydayAt(callback, hour, minute) {
  // first we need to get the time until the next hour:minute
  const now = new Date()
  // to check if the next time happens today check how many minutes
  // passed in the day and compare them with the input
  const nowInMinutes = (now.getHours() * 60) + now.getMinutes()
  const inputTimeInMinutes = (hour * 60) + minute
  const isNextTimeToday = nowInMinutes < inputTimeInMinutes

  // create a new date for the comparison
  const firstTime = new Date()
  // and set its time to the input's time
  firstTime.setHours(hour, minute, 0)

  if (!isNextTimeToday) {
    // if next time is today then add a day
    firstTime.setDate(now.getDate() + 1)
  }

  const timeUntilNextOccurrence = firstTime.getTime() - now.getTime()

  // finally set a timeout to start the first call
  // on time then every other call every 24 hours
  setTimeout(() => {
    // setInterval will start kicking in after 24 hours
    // therefore we need to invoke the first callback here
    callback()
    setInterval(callback, 1000 * 60 * 60 * 24)
  }, timeUntilNextOccurrence)
}

// to check you can try invoking it with a time that's coming soon
runEverydayAt(() => console.log('I ran!'), 10, 43)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
youssefzidan profile image
Youssef Zidan

Great!
Thanks for your feedback!
I'll check my code again and get back to you.

Collapse
 
youssefzidan profile image
Youssef Zidan • Edited

Hello!
I tried to run your function but it doesn't seem to be working.

Thread Thread
 
krimfandango profile image
Kareem Kamal

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

Image

Collapse
 
mma1979 profile image
Mohammed Abdelhay

and this one I am using regularly

// serialize javascript object into url query string
        Serialize = function (obj) {
            var str = [];
            for (var p in obj)
                if (obj.hasOwnProperty(p) && obj[p] != null && obj[p].toString() != '') {
                    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                }
            return str.join("&");
        }

Enter fullscreen mode Exit fullscreen mode
Collapse
 
youssefzidan profile image
Youssef Zidan

Nice!
I like it!

Collapse
 
endrureza profile image
Endru Reza

i think it would be good for you to create this into an npm package.

Collapse
 
youssefzidan profile image
Youssef Zidan

It's on my plan but i need to increase the number of functions.

Collapse
 
talorlanczyk profile image
TalOrlanczyk

I would like to help with the npm

Thread Thread
 
halbano profile image
halbano • Edited

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.

Thread Thread
 
youssefzidan profile image
Youssef Zidan

That's great!
Maybe we can do something together.

Collapse
 
pavlosisaris profile image
Paul Isaris

Nice collection, thanks!

Collapse
 
hellonearthis profile image
Brett Cooper

1024 = 1k bytes

Collapse
 
youssefzidan profile image
Youssef Zidan

Thanks, My friend!
I modified the article based on your feedback!

Collapse
 
metruzanca profile image
Samuele Zanca

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.

Collapse
 
youssefzidan profile image
Youssef Zidan

Thanks, My friend!
I modified the article based on your feedback!

Collapse
 
lovesponge profile image
Guy

Great Post!
I use Number.prototype.toLocaleString() to get formatted numbers 😁

Collapse
 
youssefzidan profile image
Youssef Zidan

This is amazing!
Thanks for sharing!

Collapse
 
youssefzidan profile image
Youssef Zidan

I Modified the article based on your feedback!
Thanks, my friend!

Collapse
 
nilsandrey profile image
Nils Andrey

Thanks for sharing. I recommend you to create a Github gist for most of it and share the links here.

Collapse
 
youssefzidan profile image
Youssef Zidan

Thanks, Sure I'll do so.

Collapse
 
qq449245884 profile image
qq449245884

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.

Collapse
 
youssefzidan profile image
Youssef Zidan

Sure!

Collapse
 
matthijsewoud profile image
⚡️

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

cannot hold it is too late. The force of regex and HTML together in the same conceptual space will destroy your mind like so much watery putty. If you parse HTML with regex you are giving in to Them and their blasphemous ways which doom us all to inhuman toil for the One whose Name cannot be expressed in the Basic Multilingual Plane, he comes. HTML-plus-regexp will liquify the n​erves of the sentient whilst you observe, your psyche withering in the onslaught of horror. Rege̿̔̉x-based HTML parsers are the cancer that is killing StackOverflow it is too late it is too late we cannot be saved the transgression of a chi͡ld ensures regex will consume all living tissue (except for HTML which it cannot, as previously prophesied) dear lord help us how can anyone survive this scourge using regex to parse HTML has doomed humanity to an eternity of dread torture and security holes using regex as a tool to process HTML establishes a breach between this world and the dread realm of c͒ͪo͛ͫrrupt entities (like SGML entities, but more corrupt) a mere glimpse of the world of reg​ex parsers for HTML will ins​tantly transport a programmer's consciousness into a world of ceaseless screaming, he comes, the pestilent slithy regex-infection wil​l devour your HT​ML parser, application and existence for all time like Visual Basic only worse he comes he comes do not fi​ght he com̡e̶s, ̕h̵i​s un̨ho͞ly radiańcé destro҉ying all enli̍̈́̂̈́ghtenment, HTML tags lea͠ki̧n͘g fr̶ǫm ̡yo​͟ur eye͢s̸ ̛l̕ik͏e liq​uid pain, the song of re̸gular exp​ression parsing will exti​nguish the voices of mor​tal man from the sp​here I can see it can you see ̲͚̖͔̙î̩́t̲͎̩̱͔́̋̀ it is beautiful t​he final snuffing of the lie​s of Man ALL IS LOŚ͖̩͇̗̪̏̈́T ALL I​S LOST the pon̷y he comes he c̶̮omes he comes the ich​or permeates all MY FACE MY FACE ᵒh god no NO NOO̼O​O NΘ stop the an​*̶͑̾̾​̅ͫ͏̙̤g͇̫͛͆̾ͫ̑͆l͖͉̗̩̳̟̍ͫͥͨe̠̅s ͎a̧͈͖r̽̾̈́͒͑e n​ot rè̑ͧ̌aͨl̘̝̙̃ͤ͂̾̆ ZA̡͊͠͝LGΌ ISͮ̂҉̯͈͕̹̘̱ TO͇̹̺ͅƝ̴ȳ̳ TH̘Ë͖́̉ ͠P̯͍̭O̚​N̐Y̡ H̸̡̪̯ͨ͊̽̅̾̎Ȩ̬̩̾͛ͪ̈́̀́͘ ̶̧̨̱̹̭̯ͧ̾ͬC̷̙̲̝͖ͭ̏ͥͮ͟Oͮ͏̮̪̝͍M̲̖͊̒ͪͩͬ̚̚͜Ȇ̴̟̟͙̞ͩ͌͝S̨̥̫͎̭ͯ̿̔̀ͅ
Collapse
 
sayyedhammadali profile image
Comment marked as low quality/non-constructive by the community. View Code of Conduct
Sayyed Hammad Ali

Very Nice article. Good Job.
I also wrote recently an article on medium on same topic. A list of one-line functions needed by developers on daily basis. Checkout my article here:

javascript.plainenglish.io/27-esse...