5 Javascript Utility functions I love the most ️
Tags: javascript, tips, utility, frontend
Published: 2021-08-19 13:01:27

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](https://dev.to/alvarosaburido/vite-2-a-speed-comparison-in-vue-1f5j) into a string at the end of the domain URL.

![Screenshot 2021-08-19 at 10.40.32](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s5t3pckot6zt76zidlqz.png)

This unique identifier string `vite-2-a-speed-comparison-in-vue` is what we call a [Slug](https://developer.mozilla.org/en-US/docs/Glossary/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. 

{% gist https://gist.github.com/alvarosaburido/c0306b1b5c38f6fec2d341456084fe2c %}

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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) 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.

{% gist https://gist.github.com/alvarosaburido/3d08cd76482b51c505bd86fcb210a4d6 %}

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

````javascript
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.

{% gist https://gist.github.com/alvarosaburido/72f9217b47fda741cdf08183eceec219 %}

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

You can also see the value on composing functions, on the gist example, `isEmpty` functions use `isObject` and `isArray` internally.

## 2. Deep Clone

![](https://media.giphy.com/media/ctWSqhTv0LXd6/giphy.gif?cid=790b761124a66d4a81131859987687d2fe72adc8f15de5a2&rid=giphy.gif&ct=g)

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 `Object.assign`, 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](https://mauriciogc.medium.com/javascript-shallow-copy-and-deep-copy-757bd5fb0c76) to get a deeper understanding of the topic.

{% gist https://gist.github.com/alvarosaburido/fd3c1c0459a597ef88eb4326b208475a %}

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* 

![](https://media.giphy.com/media/FP56vNcwOVyvu/giphy.gif?cid=790b761148825eb2d758dc53dba635caf16d1175d212d94b&rid=giphy.gif&ct=g)

.
.
.
.
.

## 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](https://codebrahma.com/intercepting-the-case-battle-between-snakes-and-camels-in-front-end-javascript/)), if you benchmark various business-significant APIS you will found out that by default, they use `snake-case` formatting in the JSON response instead of the beautiful and visually pleasant `camelCase` we use in the Frontend.

Let's take Github's user repositories response as an example. If you fetch mine `https://api.github.com/users/alvarosaburido/repos` you will get a response where repo info looks similar to this:

```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"
}

```

So how we can format this to be able to use `repo.fullName` or `repo.defaultBranch`? 

You could deconstruct it and assign a new variable with the camelCase, which would be very inefficient. 

I prefer to deeply format objects using this pair of utilities: 

{% gist https://gist.github.com/alvarosaburido/50c87cdd04b40b2ff624003ba3f52139 %}

BAM magic! (Not really, just recursion and regex) we can safely format the DTO and create our objects on the Frontend. 

![Screenshot 2021-08-19 at 14.54.14](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mas3f07u7p4s3l9dz7do.png)
 

It's... so..beautiful. 😭

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

## Wrap up.

That's pretty much about it, if you reach here, thank you for reading I hope this article has helped you in some way.

If you have any comments, questions, or just what to say hi, let's meet in the comment section.

Happy Coding!