5 JavaScript functions to add to your utilities library
Tags: javascript, webdev
Published: 2019-10-16 16:11:51

---
title: 5 JavaScript functions to add to your utilities library
published: true
description: 
tags: javascript, webdev
---

We all have our own utilities - dealing with date/time, validating common forms, etc, or maybe you use a third-party utility library like lodash or underscore. Either way, below is a collection of useful JavaScript functions that you can use to create or expand your **utilities library**! Enjoy and **leave your own utility functions below in the comments.**

##1. Summarize Text w/ Ellipsis
```javascript
/**
 * Accepts a string value and returns it back with an ellipsis if the string length 
 * is greater than the max length specified. Otherwise, return the original string.
 */
function summarize(str, max) {
  return str.length > max ? str.substring(0, max) + '...' : str;
}
```
Example use case (from Medium):
![Ellipsis example](https://thepracticaldev.s3.amazonaws.com/i/j7iofavhthjny1zu6md5.png)
<figcaption>Summarize an article / show preview text</figcaption>

##2. Add/remove classes on a collection of DOM objects
Extends NodeList by using prototype. It allows us to have jQuery-like functionality for adding and removing classes to multiple objects that have been selected on the DOM using querySelectorAll().

_Disclaimer: Generally speaking, extending the core JS API is not recommended, but may be useful and convenient in some isolated use-cases._
```javascript
NodeList.prototype.addClass = function(className) {
  this.forEach(el => {
    el.classList.add(className);
  });
};

NodeList.prototype.removeClass = function(className) {
  this.forEach(el => {
    el.classList.remove(className);
  });
};
```

You can then use these like so:
```javascript
// our way
document.querySelectorAll('.menu-item').addClass('disabled');
document.querySelectorAll('.menu-item').removeClass('disabled');

// standard way
const menuItems = document.querySelectorAll('.menu-item');
menuItems.forEach(el => {
  el.addClass('disabled');
});

// jQuery way
$('.menu-item').addClass('disabled');
$('.menu-item').removeClass('disabled');
```

##3. Function Performance Tester
Test the performance of your functions using console.time(). Also works on async functions as long as you use async/await.
```javascript
// outputs elapsed execution time of your method to your web console
function perfTest(name, method) {
  console.time(`Method - ${name}`);
  method.apply();
  console.timeEnd(`Method - ${name}`);
}

// usage

// function to test
function square() {
  for (let i = 0; i < 100000; i++) {
    let square = i ** 2;
  }
}

// test it
perfTest('square', square); // output -> Method - square: 3.966064453125ms
```

##4. Dynamic div Generator
If you prefer creating DOM elements dynamically, this may be useful to you. It's a way to create div elements by passing in attributes as an object.
```javascript
// creates a div, sets provided attributes, returns the div for doing whatever you want with it 
function divMe(attr) {
  const div = document.createElement('div');
  for (let i in attr) {
    div.setAttribute(i, attr[i]);
  }
  return div;
}

// usage
const div = divMe({
  class : 'blue-button',
  'data-id' : 'abc123',
  'aria-label' : 'Close'
});

document.getElementById('container').appendChild(div);
}
```

##5. Group array by key
Returns a new array that is grouped by the key that you defined. Works similarly to GROUP BY operations in SQL.
```javascript
function groupBy(arr, key) {
  return arr.reduce((acc, i) => {
    (acc[i[key]] = acc[i[key]] || []).push(i);
    return acc;
  }, {});
}

// raw data example
const roleModels = [
  {
    userId: 1,
    name: 'John Williams',
    type: 'Composer'
  },
  {
    userId: 2,
    name: 'Hans Zimmer',
    type: 'Composer'
  },
  {
    userId: 3,
    name: 'Michael Jordan',
    type: 'Athlete'
  },
  {
    userId: 4,
    name: 'J.K. Rowling',
    type: 'Author'
  }
];

const byType = groupBy(roleModels, 'type');

// results (derived):
{
  Athlete: [{...}],
  Author: [{...}],
  Composer: [
    {
      userId: 1,
      name: 'John Williams',
      type: 'Composer'
    },
    {
      userId: 2,
      name: 'Hans Zimmer',
      type: 'Composer'
    }
  ]
}
```

Utilities are an excellent way to reuse miscellaneous functions like the above. You may even organize them into modules if you wish. It's up to you! **What are some utility functions that you use all the time?** Please share in the comments below!