25 Utility Code for your next JavaScript Project

25 Utility Code for your next JavaScript Project

covering type checking, numbers, strings, arrays and, random

Introduction

When we start a new JavaScript project, often we spend so much time in writing utility code. Few prefer to include libraries which does all these utility tasks.

Including a library is acceptable if we use most of its features. But for smaller things, we can always write our own utility code.

Let's Explore

Here I will present 25 such code which you are most probably going to use in your project. Let's explore them.

➊ Check if input is of number type

/*
 * Input Type : Any
 * Output Type: Boolean
 */
function isOfNumberType(input) {
  return typeof input === 'number' ||
         input instanceof Number;
}

Examples

➀ 10 ⇨ true

➁ Number(10) ⇨ true

➂ new Number(10) ⇨ true

➃ "10" ⇨ false

➋ Check if input value contains a number

/*
 * Input Type : Any
 * Output Type: Boolean
 */
function isNumber(input) {
  return isOfNumberType(input) ||
         !isNaN(Number(input));
}

Examples

➀ 10 ⇨ true

➁ Number(10) ⇨ true

➂ new Number(10) ⇨ true

➃ "10" ⇨ true

➄ "10ABC" ⇨ false

➅ "10.01" ⇨ true

➆ "10e+14" ⇨ true

➌ Check if input value is null or, undefined

/*
 * Input Type : Any
 * Output Type: Boolean
 */
function isNullish(input) {
  return input == undefined;
}

Examples

➀ undefined ⇨ true

➁ null ⇨ true

➂ "" ⇨ false

➃ false ⇨ false

➍ Check if input value is falsy

/*
 * Input Type : Any
 * Output Type: Boolean
 */
function isFalsy(input) {
  return !input;
}

Examples

➀ undefined ⇨ true

➁ null ⇨ true

➂ { } ⇨ false

➃ [ ] ⇨ false

➄ "" ⇨ true

➅ 0 ⇨ true

➆ false ⇨ true

➎ Check if input is an Array

/*
 * Input Type : Any
 * Output Type: Boolean
 */
function isArray(input) {
  return Array.isArray(input);
}

Examples

➀ null ⇨ false

➁ [ ] ⇨ true

➂ [1, 2, 3] ⇨ true

➃ { } ⇨ false

➏ Check if input is an Empty Object

/*
 * Input Type : Object
 * Output Type: Boolean
 */
function isEmptyObject(input) {
  for (const key in input) {
    if (input.hasOwnProperty(key))
      return false;
  }
  return true;
}

Examples

➀ null ⇨ true

➁ [ ] ⇨ true

➂ { } ⇨ true

➃ {x: 10} ⇨ false

➐ Convert first character of each word to uppercase

/*
 * Input Type : String
 * Output Type: String
 */
function properCase(input) {
  return input?.toLowerCase().replace(/^\w|\s\w/g,
                                      s => s.toUpperCase());
}

Examples

➀ "" ⇨ ""

➁ "michael" ⇨ "Michael"

➂ "michael jackson" ⇨ "Michael Jackson"

➑ Convert the first character of each sentence to uppercase

/*
 * Input Type : String
 * Output Type: String
 */
function sentenceCase(input) {
  return input?.toLowerCase().replace(/(^\w)|\.\s+(\w)/gm,
                                      s => s.toUpperCase());
}

Examples

➀ "" ⇨ ""

➁ "i am bored" ⇨ "I am bored"

➂ "i am bored. let's play." ⇨ "I am bored. Let's play."

➒ Reverse a String

/*
 * Input Type : String
 * Output Type: String
 */
function reverseString(input) {
  return input?.split('').reverse().join('');
}

Examples

➀ "" ⇨ ""

➁ "Hello" ⇨ "olleH"

➂ "Hello, World!" ⇨ "!dlroW ,olleH"

➓ Convert a number from one base to another base

/*
 * Input Type(1): String
 * Input Type(2): Number
 * Input Type(3): Number
 *
 * Output Type  : String
 */
function convertBase(input, base1, base2) {
  return parseInt(input, base1).toString(base2);
}

Examples

➀ "15" | 10 | 2 ⇨ "1111"

➁ "F076" | 16 | 8 ⇨ "170166"

➊➊ Create and Initialise an array

/*
 * Input Type : Number [Length of Array]
 * Input Type : Any    [ Default Value]
 *
 * Output Type: Array
 */
function initialiseArray(length, value) {
  return Array(length).fill(value);
}

Examples

➀ 5 | 0 ⇨ [0, 0, 0, 0, 0]

➁ 0 | 5 ⇨ [ ]

➊➋ To empty an array

/*
 * Input Type : Array
 * Output Type: Array
 *
 * ⚠️ It empties the original array
 */
function emptyArray(input) {
  input?.length = 0;
  return input;
}

Examples

➀ [ ] ⇨ [ ]

➁ [1, 2, 3, 4, 5] ⇨ [ ]

➊➌ Remove blanks (falsy values) from an array

/*
 * Input Type : Array
 * Output Type: Array
 *
 * It doesn't modify the original array
 */
function removeBlanks(input) {
  return input?.filter(Boolean);
}

Examples

➀ [ ] ⇨ [ ]

➁ [1, 2, null, false, 3, undefined] ⇨ [1, 2, 3]

➊➍ Remove duplicates from an array

/*
 * Input Type : Array
 * Output Type: Array
 *
 * It doesn't modify the original array
 */
function removeDuplicates(input) {
  return [... new Set(input)];
}

Examples

➀ [ ] ⇨ [ ]

➁ [1, 2, 1, 3, 2, 4] ⇨ [1, 2, 3, 4]

➊➎ Casting an Array to Array of numbers

/*
 * Input Type : Array
 * Output Type: Array
 *
 * It doesn't modify the original array
 */
function castToNumbers(input) {
  return input?.map(Number);
}

Examples

➀ [ ] ⇨ [ ]

➁ ["1", 2, false, "3a", undefined] ⇨ [1, 2, 0, NaN, NaN]

➊➏ Return array of digits for a non-negative integer

/*
 * Input Type : Non-Negative Integer
 * Output Type: Array
 */
function digits(input) {
  return [... `${input}`].map(d => parseInt(d));
}

Examples

➀ 0 ⇨ [0]

➁ 123 ⇨ [1, 2, 3]

➂ 753289 ⇨ [7, 5, 3, 2, 8, 9]

➊➐ Return a series of integers (starting from 0)

/*
 * Input Type : Number
 * Output Type: Array
 *
 * Input shouldn't be Negative, Infinity, -Infinity, NaN
 */
function series(limit) {
  return [... Array(limit).keys()];
}

Examples

➀ 0 ⇨ [ ]

➁ 1 ⇨ [0]

➂ 10 ⇨ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

➊➑ Flatten an Array to any depth

/*
 * Input Type : Array
 * Output Type: Array
 *
 * It doesn't modify the original array
 */
function flatCompletely(input) {
  return input?.flat(Infinity);
}

Examples

➀ [1] ⇨ [1]

➁ [[[1, 2]], 3] ⇨ [1, 2, 3]

➂ [[[1, 2], 3], [[4]], 5] ⇨ [1, 2, 3, 4, 5]

➊➒ Remove holes from an Array

/*
 * Input Type : Array
 * Output Type: Array
 *
 * It doesn't modify the original array
 */
function removeHoles(input) {
  return input?.flat(0);
}

Examples

➀ [1, 2, 3] ⇨ [1, 2, 3]

➁ [1, 2, false, 3] ⇨ [1, 2, false, 3]

➂ [1, 2, null, 3] ⇨ [1, 2, null, 3]

➃ [1, 2, undefined, 3] ⇨ [1, 2, undefined, 3]

➄ [1, 2, , 3] ⇨ [1, 2, 3]

20. Merge any number of Arrays

/*
 * Input Type(s): Array(s) [Zero to Many]
 * Output Type  : Array
 *
 * It doesn't modify the original arrays
 */
function mergeArrays(...input) {
  return input?.flat(1);
}

Examples

➀ [1, 2] ⇨ [1, 2]

➁ [1, 2] | [3] ⇨ [1, 2, 3]

➂ [1, 2] | [3] | [4, [5]] ⇨ [1, 2, 3, 4, [5]]

➋➊ Shuffle an Array

/*
 * Input Type : Array
 * Output Type: Array
 *
 * ⚠️ It modifies the original array
 */
function shuffle(input) {
  return input.sort(() => Math.random() - 0.5);
}

Examples

➀ [1, 2, 3, 4, 5] ⇨ [4, 1, 3, 2, 5]

➁ [1, 2, 3, 4, 5] ⇨ [5, 2, 1, 4, 3]

➋➋ Generate Random Boolean Values

/*
 * Input Type : None
 * Output Type: Boolean
 */
function randomBoolean() {
  return Math.random() >= 0.5;
}

Examples

➀ 1st Run ⇨ true

➁ 2nd Run ⇨ false

➂ 3rd Run ⇨ false

➃ 4th Run ⇨ true

➄ 5th Run ⇨ false

The results may vary when you run yourself.

➋➌ Generate Random Numbers

/*
 * Input Type : None
 * Output Type: Number
 */
function randomInteger(min, max) {
  return Math.floor((Math.random() * (max - min + 1)) + min);
}

Examples

For inputs 3 (as min) and 10 (as max),

➀ 1st Run ⇨ 5

➁ 2nd Run ⇨ 7

➂ 3rd Run ⇨ 4

➃ 4th Run ⇨ 3

➄ 5th Run ⇨ 9

The results may vary when you run yourself.

➋➍ Generate Random ID

/*
 * Input Type : None
 * Output Type: Random Characters (0-9, A-Z, a-z)
 */
function randomID() {
  return Math.random().toString(36).substring(2) || '0';
}

Examples

➀ 1st Run ⇨ "gpr0pu9hb38"

➁ 2nd Run ⇨ "dva09gsdp9e"

The results may vary when you run yourself.

➋➎ Generate Random HEX Color Code

/*
 * Input Type : None
 * Output Type: Random 6 Characters HEX Code
 */
function randomHex() {
  return `#${(0x1000000 + Math.random() * 0xffffff).
    toString(16).slice(1, 7)}`;
}

Examples

➀ 1st Run ⇨ "#c67cbb"

➁ 2nd Run ⇨ "#4ffded"

The results may vary when you run yourself.

Final Words

We spend a lot of time in searching for these solutions. I would advice to create your own utility project and, utilise it in multiple projects.

Do you find these solutions helpful? Please give your valuable feedbacks.