25 function thường dùng trong JS

・Published on:

Check for Palindrome

const isPalindrome = str => {
    const cleaned = str.replace(/[^a-zA-Z0-9]/g, **).toLowerCase();
    return cleaned === cleaned.split("").reverse().join("");
}

Fetch JSON Data

const fetchJson = async url => (await fetch(url)).json();

Random Color Generator

const getRandomColor = () => `#${Math.floor(Math.random() * 16777215).toString(16)}`;

Convert String to Title Case

const toTitleCase = str => str.toLowerCase().split(' ')
    .map(word => word.charAt(0). toUpperCase) + word.slice(1))
    .join(' ');

Convert Camel Case to Snake Case

const camelToSnake = str => str.replace(/([A-Z])/g, "_$1").toLowerCase();

Get URL Parameters

const getUrlParams = () => Object.fromEntries(new URLSearchParams(window.location.search));

Capitalize First Letter of Each Word

const capitalizeWords = str => str.replace(/\b\w/g, char => char.toUpperCase());

Check if Object is Empty

const isEmptyObject = obj => Object.keys(obj).length === 0;

Remove Specific Item from Array

const removeItem = (arr, item) => arr.filter(it => it !== item);

Check for Anagram

const areAnagrams = (str1, str2) => {
    const normalize = str => str.split('').sort().join('');
    return normalize(str1) === normalize(str2);
}

Convert Object to Query String

const toQueryString = obj => Object.keys(obj).map(key =>
    `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`
).join('&');

Delay Execution

const delay = (func, ms) => setTimeout (func, ms);

Generate UUID

const generateUUID = () => 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => (Math.random() * 16 | 0).toString(16));

Get Random Element from Array

const getRandomElement = arr => arr[Math.floor(Math.random() * arr.length)];

Convert Celsius to Fahrenheit

const celsiusToFahrenheit = celsius => (celsius * 9/5) + 32;

Get Unique Values from Array

const unique = arr = [...new Set(arr)];

Sum of Array Elements

const sumArray = arr => arr.reduce(ace, curr) => acc + curr, 0);

Get Distinct Characters in String

const distinctCharacters = str => [...new Set(str)].join('');

Convert Array to Object

const arrayTobject = (arr, key) => arr.reduce((obj, item) => {
    obj[item[key]] = item; 
    return obj;
}), {});

Count Occurrences in Array

const countOccurrences = arr => arr.reduce((acc, item) => { 
   acc[item] = (acc[item] || 0) + 1; 
   return acc; 
}. {});

Deep Clone Object

const deepClone = obj => JSON.parse(JSON.stringify(obj));

Random Number Generator

function getRandomNumber(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

Check if Array is Empty

const isEmptyArray = arr => Array.isArray(arr) && arr.length === 0;

Unique Array Elements

const uniqueArray = arr => [...new Set(arr)];

Get Current Date and Time

const getCurrentDateTime = () => new Date().toLocaleString();

Flatten Nested Arrays

const flattenArray = arr => arr.flat(Infinity);

Sort an Array of Objects

const sortByKey = (array, key) => array.sort((a, b) => (a[key] > b[key]) ? 1 : -1);

Check if Number is Even or Odd

const isEven = num => num * 2 === 0;

Append Search params

const [search, setSearch] = useSearchParams()

setSearch(prevParams => ({
    ...Object.fromEntries(prevParams.entries()),
    ...newSearchParams,
});

Use boolean hook

import { useState, useCallback } from 'react';

// ----------------------------------------------------------------------

export interface UseBooleanReturnType {
  value: boolean;
  onTrue: () => void;
  onFalse: () => void;
  onToggle: () => void;
  setValue: React.Dispatch<React.SetStateAction<boolean>>;
}

export function useBoolean(defaultValue?: boolean): UseBooleanReturnType {
  const [value, setValue] = useState(!!defaultValue);

  const onTrue = useCallback(() => {
    setValue(true);
  }, []);

  const onFalse = useCallback(() => {
    setValue(false);
  }, []);

  const onToggle = useCallback(() => {
    setValue((prev) => !prev);
  }, []);

  return {
    value,
    onTrue,
    onFalse,
    onToggle,
    setValue,
  };
}

Convert các kí tự tiếng Việt sang không dấu

function toNonAccentVietnamese(str) {
  return decodeURI(str).normalize('NFC')
      .replace(/Á|À|Ả|Ã|Ạ|Â|Ấ|Ầ|Ẫ|Ẩ|Ậ|Ă|Ắ|Ằ|Ẵ|Ặ|ẳ/g, "A")
      .replace(/á|à|ả|ã|ạ|â|ấ|ầ|ẫ|ẩ|ậ|ă|ắ|ằ|ẵ|ặ|ẳ/g, "a")
      .replace(/É|È|Ẻ|Ẽ|Ẹ|Ê|Ế|Ề|Ể|Ễ|Ệ/g, "E")
      .replace(/é|è|ẻ|ẽ|ẹ|ê|ề|ế|ệ|ể|ễ/g, "e")
      .replace(/Í|Ì|Ỉ|Ĩ|Ị/g, "I")
      .replace(/ì|í|ị|ỉ|ĩ/g, "i")
      .replace(/Ó|Ò|Ỏ|Õ|Ọ|Ô|Ố|Ồ|Ỗ|Ộ|Ổ|Ơ|Ớ|Ờ|Ỡ|Ợ|Ở/g, "O")
      .replace(/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ/g, "o")
      .replace(/Ú|Ù|Ủ|Ũ|Ụ|Ư|Ứ|Ừ|Ữ|Ử|Ự/g, "U")
      .replace(/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ/g, "u")
      .replace(/Ý|Ỳ|Ỷ|Ỹ|Ỵ/g, "Y")
      .replace(/ỳ|ý|ỵ|ỷ|ỹ/g, "y")
      .replace(/Đ/g, "D")
      .replace(/đ/g, "d")
}