26

Author: YoussefZidan
Translator: Frontend Xiaozhi
Source: dev

There are dreams and dry goods. search 16189ba0b5555b [Great Move to the World] Follow the brushing wisdom who is still doing dishes in the early morning.

This article GitHub https://github.com/qq449245884/xiaozhi has been included, the first-line interview complete test site, information and my series of articles.

Last month spent 1,600 to build a higher configuration Alibaba server to learn node and the corresponding framework, now: Alibaba Cloud Double 11 event 1 core 2G1M, 69 yuan / 1 year, 180 yuan / 3 years

In this article, I will share some functions that I use in almost every project.

randomNumber()


Get the random number in the specified interval.

**
 * 在最小值和最大值之间生成随机整数。
 * @param {number} min Min number
 * @param {number} max Max Number
 */
export const randomNumber = (min = 0, max = 1000) =>
  Math.ceil(min + Math.random() * (max - min));

// Example
console.log(randomNumber()); // 97 

capitalize()


Capitalize the first letter of the string.

/**
 * Capitalize Strings.
 * @param {string} s String that will be Capitalized
 */
export const capitalize = (s) => {
  if (typeof s !== "string") return "";
  return s.charAt(0).toUpperCase() + s.slice(1);
}

// Example
console.log(capitalize("cat")); // Cat

truncate();


This is useful for long strings, especially inside tables.

/**
 * 截断字符串....
 * @param {string} 要截断的文本字符串
 * @param {number} 截断的长度
 */
export const truncate = (text, num = 10) => {
  if (text.length > num) {
    return `${text.substring(0, num - 3)}...`
  }
  return text;
}

// Example
console.log(truncate("this is some long string to be truncated"));  

// this is... 

toTop();


Scroll to the bottom, you can specify the scroll speed state behavior

/**
 * Scroll to top
 */
export const toTop = () => {
  window.scroll({ top: 0, left: 0, behavior: "smooth" });
}; 

softDeepClone()


This method is often used, because with it, we can deep clone nested arrays or objects.

However, this function cannot work with data types such as new Date() , NaN , undefined , function , Number , Infinity

You want to clone depth data types described above, may be used lodash in cloneDeep() function.

/**
 * Deep cloning inputs
 * @param {any} input Input
 */
export const softDeepClone= (input) => JSON.parse(JSON.stringify(input));

appendURLParams() & getURLParams()


Quickly add and get query string methods, I usually use them to store the pagination metadata to url .

/**
 * Appen query string and return the value in a query string format.
 * @param {string} key
 * @param {string} value
 */
export const appendURLParams = (key, value) => {
  const searchParams = new URLSearchParams(window.location.search).set(key, value);
  return searchParams.toString();
};

// example
console.log(appendURLParams("name", "youssef")) // name=youssef

/**
 * Get param name from URL.
 * @param {string} name
 */
export const getURLParams = (name) => new URLSearchParams(window.location.search).get(name);

// Example
console.log(getURLParams(id)) // 5

getInnerHTML()


Whenever the server returns a string of HTML elements, I will use it.

/**
 * 获取HTML字符串的内部Text
 * @param {string} str A string of HTML
 */
export const getInnerHTML = (str) => str.replace(/(<([^>]+)>)/gi, "");

scrollToHide()


Scroll up to show HTML elements, scroll down to hide them.


/**
 * 下滚动时隐藏HTML元素。
 * @param {string} 元素的 id
 * @param {string} distance in px ex: "100px"
 */
export const scrollToHide = (id, distance) => {
  let prevScrollpos = window.pageYOffset;
  window.onscroll = () => {
    const currentScrollPos = window.pageYOffset;
    if (prevScrollpos > currentScrollPos) {
      document.getElementById(id).style.transform = `translateY(${distance})`;
    } else {
      document.getElementById(id).style.transform = `translateY(-${distance})`;
    }
    prevScrollpos = currentScrollPos;
  };
};

humanFileSize ()


Pass in the file in bytes, and return to the unit we are familiar with every day.

/**
 * Converting Bytes to Readable Human File Sizes.
 * @param {number} bytes Bytes in Number
 */
export const humanFileSize = (bytes) => {
  let BYTES = bytes;
  const thresh = 1024;

  if (Math.abs(BYTES) < thresh) {
    return `${BYTES} B`;
  }

  const units = ["kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];

  let u = -1;
  const r = 10 ** 1;

  do {
    BYTES /= thresh;
    u += 1;
  } while (Math.round(Math.abs(BYTES) * r) / r >= thresh && u < units.length - 1);

  return `${BYTES.toFixed(1)} ${units[u]}`;
};

// Example
console.log(humanFileSize(456465465)); // 456.5 MB

getTimes()


Do you have a DDL that displays the time of day every n minutes? Use this function.

/**
 * Getting an Array of Times + "AM" or "PM".
 * @param {number} minutesInterval
 * @param {number} startTime 
 */
export const getTimes = (minutesInterval = 15, startTime = 60) => {
  const times = []; // time array
  const x = minutesInterval; // minutes interval
  let tt = startTime; // start time
  const ap = ["AM", "PM"]; // AM-PM

  // loop to increment the time and push results in array
  for (let i = 0; tt < 24 * 60; i += 1) {
    const hh = Math.floor(tt / 60); // getting hours of day in 0-24 format
    const mm = tt % 60; // getting minutes of the hour in 0-55 format
    times[i] = `${`${hh === 12 ? 12 : hh % 12}`.slice(-2)}:${`0${mm}`.slice(-2)} ${
      ap[Math.floor(hh / 12)]
    }`; // pushing data in array in [00:00 - 12:00 AM/PM format]
    tt += x;
  }
  return times;
};

// Example
console.log(getTimes());
/* [
    "1:00 AM",
    "1:15 AM",
    "1:30 AM",
    "1:45 AM",
    "2:00 AM",
    "2:15 AM",
    "2:30 AM",
    // ....
    ]
*/ 

setLocalItem() & getLocalItem()

Let LocalStorage have an expiration time.

/**
 * Caching values with expiry date to the LocalHost.
 * @param {string} key Local Storage Key
 * @param {any} value Local Storage Value
 * @param {number} ttl Time to live (Expiry Date in MS)
 */
export const setLocalItem = (key, value, ttl = duration.month) => {
  const now = new Date();
  // `item` is an object which contains the original value
  // as well as the time when it's supposed to expire
  const item = {
    value,
    expiry: now.getTime() + ttl,
  };
  localStorage.setItem(key, JSON.stringify(item));
};

/**
 * Getting values with expiry date from LocalHost that stored with `setLocalItem`.
 * @param {string} key Local Storage Key
 */
export const getLocalItem = (key) => {
  const itemStr = localStorage.getItem(key);
  // if the item doesn't exist, return null
  if (!itemStr) {
    return null;
  }
  const item = JSON.parse(itemStr);
  const now = new Date();
  // compare the expiry time of the item with the current time
  if (now.getTime() > item.expiry) {
    // If the item is expired, delete the item from storage
    // and return null
    localStorage.removeItem(key);
    return null;
  }
  return item.value;
}; 

formatNumber()


/**
 * Format numbers with separators.
 * @param {number} num
 */
export const formatNumber = (num) => num.toLocaleString();

// Example
console.log(formatNumber(78899985)); // 78,899,985

We can also add other options to get other number formats, such as currency, distance, weight, etc.

export const toEGPCurrency = (num) =>
  num.toLocaleString("ar-EG", { style: "currency", currency: "EGP" });

export const toUSDCurrency = (num) =>
  num.toLocaleString("en-US", { style: "currency", currency: "USD" });

console.log(toUSDCurrency(78899985)); // $78,899,985.00
console.log(toEGPCurrency(78899985)); // ٧٨٬٨٩٩٬٩٨٥٫٠٠ ج.م.

toFormData()

Whenever I need to send a file to the server, I use this function.

/**
 * Convert Objects to Form Data Format.
 * @param {object} obj
 */
export const toFormData = (obj) => {
  const formBody = new FormData();
  Object.keys(obj).forEach((key) => {
    formBody.append(key, obj[key])
  })
  
  return formBody;
}

getScreenWidth()

Get a string representing the width of the screen.

/**
 * Detect screen width and returns a string representing the width of the screen.
 */
export const getScreenWidth = () => {
  const screenWidth = window.screen.width;
  if (screenWidth <= 425) return "mobile";
  if (screenWidth <= 768) return "tablet";
  if (screenWidth <= 1024) return "laptopSm";
  if (screenWidth <= 1440) return "laptopLg";
  if (screenWidth <= 2560) return "HD";
  return screenWidth;
}; 

Check whether each element in the array exists in another array.

export const containsAll = (baseArr, arr) => {
  let all = false;

  for (let i = 0; i < arr.length; i += 1) {
    if (baseArr.includes(arr[i])) {
      all = true;
    } else {
      all = false;
      return all;
    }
  }

  return all;
};

Do you have any other useful functions? How about sharing it in the comments?

Finish~, I’m Xiaozhi, I’m going to clean the dishes.


possible bugs that may exist after 16189ba0b55a3c code is deployed cannot be known in real time. In order to solve these bugs afterwards, a lot of time was spent on log debugging. By the way, I would like to recommend a useful BUG monitoring tool Fundebug .

Original: https://dev.to/youssefzidan/javascript-functions-that-will-make-your-life-much-easier-1imh

comminicate

The article is continuously updated every week, you can search for [Daqichang World] Read it for the first time, reply [Benefit] are multiple front-end videos waiting for you, this article GitHub https://github.com/qq449245884/xiaozhi has been included, welcome to Star.


王大冶
68.1k 声望105k 粉丝