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!