5 Javascript Utility functions I love the most ️

alvarosabu

Alvaro Saburido

Posted on August 19, 2021

5 Javascript Utility functions I love the most ️

Despite all the "trendy" tweets complaining about Javascript being too difficult (most coming from non-users 😅), Javascript is a marvelous language that allows us to create amazing stuff on the web.

Sometimes we found ourselves doing the same cool stuff over and over again in our projects, it could be a function to format the response of an API, to format dates, to check the current browser used.

What do we do if we have a function we need to re-use across the same project? We create a utility function.

In this article, I want to share my top 5 favorite Javascript utility functions that I use constantly on my projects. As a warning ⚠️, I'm not including methods like map, reduce, filter because they are built-in on the standard and do not require any customization.

Second disclaimer ⚠️, this article is very opinionated, I'm not a Javascript Guru, this is based on my personal likes and some of them maybe have a better way to be done, if so, don't hesitate to comment on your opinion & improvements, constructive feedback is well received.

5. Slugify

Sometimes we need to programmatically format a blog post title like one of my previous posts Vite 2 - A speed comparison in Vue into a string at the end of the domain URL.

Screenshot 2021-08-19 at 10.40.32

This unique identifier string vite-2-a-speed-comparison-in-vue is what we call a Slug

As a standard, the slug formatting should be:

  • lowercase: to avoid casing issues.
  • use of -: spaces and multiple '-' should be replaced with single '-'.
  • trimmed: from the start of the text.

The function takes a string parameter (in case of using Javascript only, use .toString() to ensure that the parameter is converted to string), then we use toLowerCase() to remove any casings and take advantage of the power of Regex to ensure all the previous requirements listed are fulfilled.

4. Mock Async

This one is especially versatile, let's put ourselves in context.

There will be times you will not have access to the Rest API or the BE team is low on capacity and you need to move forward the Frontend part of a ticket beforehand. I know, it's not ideal, but this utility becomes handy to test async code (like an API call) and be able to easily integrate your code once BE work is done.

Async === Promises so we basically create a new Promise with a setTimeout that resolves or reject depending on a boolean parameter.

const fakeAPICall = (success, timeout, value) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (success) {
        resolve(value);
      } else {
        reject({ message: 'Error' });
      }
    }, timeout);
  });
};

async function loadPosts() {
   try {
      const { data } = await fakeAPICall(true, 2000, 
      MOCK_POSTS_RESPONSE);

      return data.posts;

   }, catch(error) {
     // Do what you need to do
   }
}
```



Another perfect fit for this function is testing async behaviors in **unit testing** like error handling on a component.

## 3. Is utility functions

I might be cheating here so I apologize in advance because this one is not a single utility function but a bunch of them.

They're straightforward enough but yet so powerful on everyday code. You need to conditionally check if the parameter of a function is an </span><span class="nb">Object</span><span class="s2"> or an </span><span class="nb">Array</span><span class="s2">? You got it </span><span class="nx">isObject</span><span class="s2"> and </span><span class="nx">isArray</span><span class="s2"> . Need to check if the browser is Safari (I hope you don't need to) you got </span><span class="nx">isSafari</span><span class="s2">.

You can also see the value on composing functions, on the gist example, </span><span class="nx">isEmpty</span><span class="s2"> functions use </span><span class="nx">isObject</span><span class="s2"> and </span><span class="nx">isArray</span><span class="s2"> internally.

 2. Deep Clone

This one still makes me very nervous. I remember spending hours and hours on a good solution to copy a deeply nested object or array into a new one without referencing (to avoid mutations).

Javascript offers several Shallow Copy options like </span><span class="nb">Object</span><span class="p">.</span><span class="nx">assign</span><span class="s2">, the problem with those is that even if it creates an exact copy of the original object, if any of the properties is itself an object or array, it will copy the reference to that object. Check this article to get a deeper understanding of the topic.

What this function does essentially, is recursively (remember we might have nested objects inside arrays inside nested objects, infinite possibilities) check if the value of a property is a simple value or more complex and iterate into all the keys internally.

The result is an exact copy of the original item without references.

That brings us to the number one, drumrolls please

.
.
.
.
.

 1. 🎉 snakeToCamel (🐍 to 🐫)

Frontend and Backend Developers we are indeed, very different creatures, but if there is anything that separates us the most is:

> How we case our properties.

Jokes aside (there is a really funny article about it here), if you benchmark various business-significant APIS you will found out that by default, they use </span><span class="nx">snake</span><span class="o">-</span><span class="k">case</span><span class="s2"> formatting in the JSON response instead of the beautiful and visually pleasant </span><span class="nx">camelCase</span><span class="s2"> we use in the Frontend.

Let's take Github's user repositories response as an example. If you fetch mine </span><span class="nx">https</span><span class="p">:</span><span class="c1">//api.github.com/users/alvarosaburido/repos you will get a response where repo info looks similar to this:


{% raw %}

```JSON
{
"id": 337852842,
"node_id": "MDEwOlJlcG9zaXRvcnkzMzc4NTI4NDI=",
"name": "alvaro-dev-labs-",
"full_name": "alvarosaburido/alvaro-dev-labs-",
"private": false,
"homepage": null,
"size": 53,
"stargazers_count": 0,
"watchers_count": 0,
"language": "JavaScript",
"has_issues": true,
"has_projects": true,
"has_downloads": true,
"has_wiki": true,
"has_pages": false,
"forks_count": 1,
"mirror_url": null,
"archived": false,
"disabled": false,
"open_issues_count": 1,
"license": null,
"forks": 1,
"open_issues": 1,
"watchers": 0,
"default_branch": "main"
}

<span class="p">{</span><span class="o">%</span> <span class="nx">endraw</span> <span class="o">%</span><span class="p">}</span>


<span class="nx">So</span> <span class="nx">how</span> <span class="nx">we</span> <span class="nx">can</span> <span class="nx">format</span> <span class="k">this</span> <span class="nx">to</span> <span class="nx">be</span> <span class="nx">able</span> <span class="nx">to</span> <span class="nx">use</span> <span class="p">{</span><span class="o">%</span> <span class="nx">raw</span> <span class="o">%</span><span class="p">}</span><span class="s2">`repo.fullName`</span><span class="p">{</span><span class="o">%</span> <span class="nx">endraw</span> <span class="o">%</span><span class="p">}</span> <span class="nx">or</span> <span class="p">{</span><span class="o">%</span> <span class="nx">raw</span> <span class="o">%</span><span class="p">}</span><span class="s2">`repo.defaultBranch`</span><span class="p">{</span><span class="o">%</span> <span class="nx">endraw</span> <span class="o">%</span><span class="p">}?</span> 

<span class="nx">You</span> <span class="nx">could</span> <span class="nx">deconstruct</span> <span class="nx">it</span> <span class="nx">and</span> <span class="nx">assign</span> <span class="nx">a</span> <span class="k">new</span> <span class="nx">variable</span> <span class="kd">with</span> <span class="nx">the</span> <span class="nx">camelCase</span><span class="p">,</span> <span class="nx">which</span> <span class="nx">would</span> <span class="nx">be</span> <span class="nx">very</span> <span class="nx">inefficient</span><span class="p">.</span> 

<span class="nx">I</span> <span class="nx">prefer</span> <span class="nx">to</span> <span class="nx">deeply</span> <span class="nx">format</span> <span class="nx">objects</span> <span class="nx">using</span> <span class="k">this</span> <span class="nx">pair</span> <span class="k">of</span> <span class="nx">utilities</span><span class="p">:</span> 

<span class="p">{</span><span class="o">%</span> <span class="nx">gist</span> <span class="na">https</span><span class="p">:</span><span class="c1">//gist.github.com/alvarosaburido/50c87cdd04b40b2ff624003ba3f52139 %}</span>

<span class="nx">BAM</span> <span class="nx">magic</span><span class="o">!</span> <span class="p">(</span><span class="nx">Not</span> <span class="nx">really</span><span class="p">,</span> <span class="nx">just</span> <span class="nx">recursion</span> <span class="nx">and</span> <span class="nx">regex</span><span class="p">)</span> <span class="nx">we</span> <span class="nx">can</span> <span class="nx">safely</span> <span class="nx">format</span> <span class="nx">the</span> <span class="nx">DTO</span> <span class="nx">and</span> <span class="nx">create</span> <span class="nx">our</span> <span class="nx">objects</span> <span class="nx">on</span> <span class="nx">the</span> <span class="nx">Frontend</span><span class="p">.</span> 

<span class="o">!</span><span class="p">[</span><span class="nx">Screenshot</span> <span class="mi">2021</span><span class="o">-</span><span class="mi">08</span><span class="o">-</span><span class="mi">19</span> <span class="nx">at</span> <span class="mf">14.54</span><span class="p">.</span><span class="mi">14</span><span class="p">](</span><span class="na">https</span><span class="p">:</span><span class="c1">//dev-to-uploads.s3.amazonaws.com/uploads/articles/mas3f07u7p4s3l9dz7do.png)</span>


<span class="nx">It</span><span class="dl">'</span><span class="s1">s... so..beautiful. 😭

![](https://media.giphy.com/media/gwBouIIUuVvuE/giphy.gif?cid=ecf05e47703j81z92q1kqapqxkd69ko9ghk2105bedpns7ut&amp;rid=giphy.gif&amp;ct=g)  

## Wrap up.

That</span><span class="dl">'</span><span class="nx">s</span> <span class="nx">pretty</span> <span class="nx">much</span> <span class="nx">about</span> <span class="nx">it</span><span class="p">,</span> <span class="k">if</span> <span class="nx">you</span> <span class="nx">reach</span> <span class="nx">here</span><span class="p">,</span> <span class="nx">thank</span> <span class="nx">you</span> <span class="k">for</span> <span class="nx">reading</span> <span class="nx">I</span> <span class="nx">hope</span> <span class="k">this</span> <span class="nx">article</span> <span class="nx">has</span> <span class="nx">helped</span> <span class="nx">you</span> <span class="k">in</span> <span class="nx">some</span> <span class="nx">way</span><span class="p">.</span>

<span class="nx">If</span> <span class="nx">you</span> <span class="nx">have</span> <span class="nx">any</span> <span class="nx">comments</span><span class="p">,</span> <span class="nx">questions</span><span class="p">,</span> <span class="nx">or</span> <span class="nx">just</span> <span class="nx">what</span> <span class="nx">to</span> <span class="nx">say</span> <span class="nx">hi</span><span class="p">,</span> <span class="kd">let</span><span class="dl">'</span><span class="s1">s meet in the comment section.

Happy Coding!
</span></code></pre></div>
Enter fullscreen mode Exit fullscreen mode
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
alvarosabu
Alvaro Saburido

Posted on August 19, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related