DEV Community

John Serrao
John Serrao

Posted on

Handy JS Methods and Utility Functions

This is just a list of little helpers I end up using in a lot of my applications. I'll try to add to it as time goes on. The following are listed alphabetically by function name.

A

/**
 * arrayShuffle...drum roll please...shuffles an array
 * The idea is to introduce some randomness into things
 * The array is directly modified, not immutable
 *  
 * This is the Fisher-Yates randomization method
 * The idea is to count down from the back of the array
 * As you go, you randomly pick a random one before it 
 * 
 * 
 * @param { array } array - array you want to shuffle 
 */

export function arrayShuffle(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));

    // Basically we destructure the current and adjacent array indicies
    // Then we swap them around, with j being a randomized index
    [array[i], array[j]] = [array[j], array[i]];
  }
}
Enter fullscreen mode Exit fullscreen mode

D

/**
 * dateFormatter()
 * 
 * Desc: Takes an ISO 8601 date, and gives back an object:
 * 
 *    unixTime, a Unix integer timestamp (milliseconds since 1970-01-01, ie 1546300800000)
 *    month, full name of month (ie, "July")
 *    day, string with date and suffix (ie, "5th", "13th")
 *    year, 4 digit representation of the year (ie, "2021")
 *
 * Note: this uses setDateSuffix() listed below...
 * 
 * @param { string } ISOdate - expects ISO 8601 date
 */
 export const dateFormatter = (ISOdate) => {

  // Parse date from ISO format
  const newDate = new Date(ISOdate)

  // Set up obj for results
  // using a lot of date methods, check this out if you're rusty on dates:
  // https://stackoverflow.com/questions/4321270/regarding-javascript-new-date-and-date-parse/66823255#66823255
  return {
    unixTime: Date.parse(newDate),
    month: newDate.toLocaleString('en-us', { month: 'long' } ),
    day: setDateSuffix(newDate.getDate()),
    year: newDate.getFullYear()
  }
}
Enter fullscreen mode Exit fullscreen mode

R

/**
 * randomID() - generates sufficiently random numbers for React key IDs
 * @param { int } num - however random you want it
 */
export const randomID = (num) => { 
  return Math.round(Math.random() * num) 
}
Enter fullscreen mode Exit fullscreen mode

S

/**
 * setDateSuffix()
 * 
 * Desc: Takes two digit date, adds 'st', 'nd', 'rd', etc
 * 
 * @param { integer } num - a number date
 */

 export const setDateSuffix = (num) => {
  const j = num % 10,
        k = num % 100

  if (j === 1 && k !== 11) {
    return num + "st";
  }
  if (j === 2 && k !== 12) {
    return num + "nd";
  }
  if (j === 3 && k !== 13) {
    return num + "rd";
  }

  return num + "th";
}
Enter fullscreen mode Exit fullscreen mode

T

// Type detection in JS
if(typeof(image) === 'string') {
  // do work
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)