편리한 JS 메소드 및 유틸리티 함수

9155 단어 javascript
이것은 내가 많은 응용 프로그램에서 결국 사용하게 되는 작은 도우미의 목록일 뿐입니다. 시간나는대로 추가해보려고 합니다. 다음은 기능 이름의 알파벳순으로 나열됩니다.




/**
 * 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]];
  }
}





/**
 * 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()
  }
}


아르 자형




/**
 * 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) 
}


에스




/**
 * 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";
}





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

좋은 웹페이지 즐겨찾기