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;