Preface
In this post, I listed a series of 50 JavaScript single-line codes that are very useful when developing with vanilla js (≥ ES6). They are also an elegant way to solve problems using all the features that the language has provided us in the latest version.
I divided them into the following 5 categories:
- date
- String
- number
- Array
- tool
Without further ado, I'll start right away, and I hope you find them helpful to you!
date
1. Is the date correct (valid)
This method is used to check if a given date is valid
const isDateValid = (...val) => !(new Date(...val).valueOf()); isDateValid("December 27, 2022 13:14:00"); // true
2. Know whether a date corresponds to the current date
It's as simple as converting two dates to the same format and comparing them.
is a Date instance.
const isCurrentDay = (date) => new Date().toISOString().slice(0, 10) === ().slice(0, 10);
3. How to know if a date is between two dates
We check if past dates are within the minimum-maximum range.
<min>, <max>, and <date> are Date instances.
const isBetweenTwoDates = ( min, max, date) => () >= () && () <= ();
4. Calculate the interval between two dates
This method is used to calculate the interval between two dates.
const dayDif = (date1, date2) => ((() - ()) / 86400000) dayDif(new Date("2022-08-27"), new Date("2022-12-25")) // 120
5. How to know if a date is on the weekend
The getDay method returns a number between 0 and 6, indicating that the given date is the day of the week.
is a Date instance.
const isWeekend = ( date ) => () === 6 || () === 0;
6. Check if the date is within one year
Similar to what we used to check if a date corresponds to the current date. In this case, we take the years and compare them.
and are two Date instances.
const isInAYear = (date, year) => () === new Date(`${year}`).getUTCFullYear();
7. Determine which day of the year the date is
This method is used to detect which day of the year the given date resides.
const dayOfYear = (date) => ((date - new Date((), 0, 0)) / 1000 / 60 / 60 / 24); dayOfYear(new Date()); // 239
8. Convert hours to AM-PM format
We can use mathematical expressions to judge whether the elapsed time is less than or equal to 13 hours, so as to determine whether it is "morning" or "afternoon".
const toAMPMFormat= (h) => `${h % 12 === 0 ? 12 : h % 12}${h < 12 ? ' am.' : ' pm.'}`;
9. Format time
This method can be used to convert time to hh:mm:ss format.
const timeFromDate = date => ().slice(0, 8); timeFromDate(new Date(2021, 11, 2, 12, 30, 0)); // 12:30:00 timeFromDate(new Date()); // now time 09:00:00
10. Convert hours to AM-PM format
We can use mathematical expressions to judge whether the elapsed time is less than or equal to 13 hours, so as to determine whether it is "morning" or "afternoon".
const toAMPMFormat= (h) => `${h % 12 === 0 ? 12 : h % 12}${h < 12 ? ' am.' : ' pm.'}`;
String
10.1 Initial capitalization of string
This method is used to capitalize the first letter of a string.
const capitalize = str => (0).toUpperCase() + (1) capitalize("hello world") // Hello world
10.2 Capitalization of the first letter of the sentence
We convert the first letter to capital letter and then use <join.> to attach the rest of the letters of the sentence
const capitalize = ([first, ...rest]) => `${()}${('')}`;
11. Convert a letter to his colleague's emoji
const letterToEmoji = c => (().charCodeAt() + 127365);
12. How to determine whether a string is a backdrop
const isPalindrome = (str) => () === ().split('').reverse().join('');
13. Flip string
This method is used to flip a string and return the flipped string.
const reverse = str => ('').reverse().join(''); reverse('hello world'); // 'dlrow olleh'
14. Random strings
This method is used to generate random strings.
//Method Oneconst randomString = () => ().toString(36).slice(2); randomString(); //Method 2const randomstr = ().toString(36).substring(7)
15. String truncation
This method truncates the string to a specified length.
const truncateString = (string, length) => < length ? string : `${(0, length - 3)}...`; truncateString('Hi, I should be truncated because I am too loooong!', 36) // 'Hi, I should be truncated because...'
16. Remove HTML from string
This method is used to remove HTML elements from a string.
const stripHtml = html => (new DOMParser().parseFromString(html,'text/html')). || '';
number
17. How to calculate the factorial of a number
const getFactorial = (n) => (n <= 1 ? 1 : n * getFactorial(n - 1));
18. How to get a Fibonacci sequence of a number
const getFibonacci = (n, memo = {}) => memo[n] || (n <= 2 ? 1 : (memo[n] = getFibonacci(n - 1, memo) + getFibonacci(n - 2, memo)));
19. How to find the factorial of a number
const getFactorial = (n) => (n <= 1 ? 1 : n * getFactorial(n - 1));
20. Determine whether a number is an odd or even number
This method is used to determine whether a number is an odd or even number.
const isEven = num => num % 2 === 0; isEven(996);
21. Get the average of a set of numbers
const average = (.. .args) => ((a, b) => a + b) / ; average(1, 2, 3, 4, 5); // 3
22. Determine a random integer from two integers
This method is used to get a random integer between two integers.
const random = (min, max) => (() * (max — min + 1) + min); random(1, 50);
23. Round to the specified number of digits
This method can be used to round the number to the specified number.
const random = (min, max) => (() * (max — min + 1) + min); random(1, 50);
Array
24. Copy an array to another array
const copyToArray = (arr) => [...arr];
25. Get unique elements from array
const getUnique = (arr) => [...new Set(arr)];
26. Random arrangement
The following code snippet disrupts the array in a very efficient way.
const shuffle = (arr) => (() => () - 0.5);
27. Group arrays by attributes
const groupBy = (arr, groupFn) => ( (grouped, obj) => ({...grouped, [groupFn(obj)]: [...(grouped[groupFn(obj)] || []), obj], }),{});
28. Check whether two arrays contain the same value
We can use the () and () methods to check whether the two arrays contain the same value.
const containSameValues= (arr1, arr2) => ().join(',') === ().join(',');
tool
29. Detect whether the object is empty
This method is used to detect whether a JavaScript object is empty.
const isEmpty = obj => (obj).length === 0 && === Object;
30. Switch variables
The following form can be used to exchange the values of two variables without applying a third variable.
[foo, bar] = [bar, foo];
31. Random boolean value
This method returns a random boolean value. Using (), you can get a random number of 0-1 and compare it to 0.5, with half the probability of getting a true or false value.
const randomBoolean = () => () >= 0.5; randomBoolean();
32. Get the type of variable
This method is used to get the type of a variable.
const trueTypeOf = (obj) => (obj).slice(8, -1).toLowerCase(); trueTypeOf(‘'); // string trueTypeOf(0); // number trueTypeOf(); // undefined trueTypeOf(null); // null trueTypeOf({}); // object trueTypeOf([]); // array trueTypeOf(0); // number trueTypeOf(() => {}); // function
33. Color conversion
33.1 Convert HEX "#00000" to RGB(0,0,0)
const toRGB= (hex) => hex. replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i, (_, r, g, b) => `#${r}${r}${g}${g}${b}${b}`) .substring(1) .match(/.{2}/g) .map((x) => parseInt(x, 16));
33.2 Convert RGB(0,0,0) to HEX"#00000"
const rgbToHex= (r,g,b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); rgbToHex(255, 255, 255); // '#ffffff'
33.3 Randomly generate a hexadecimal color
This method is used to get random hexadecimal (HEX) color values.
const randomHex = () => `#${(() * 0xffffff).toString(16).padEnd(6, "0")}`; randomHex();
34. Temperature and Fahrenheit conversion
34.1 Convert to Fahrenheit
const toFahrenheit= (celsius) => (celsius * 9) / 5 + 32;
34.2 Convert to Celsius
const toCelsius= (fahrenheit) => (fahrenheit- 32) * 5 / 9;
35. Determine if the current tab is active
This method is used to check if the current tab is active.
const isTabInView = () => !;
36. Determine whether the current device is an Apple device
This method is used to check if the current device is an Apple device.
const isAppleDevice = () => /Mac|iPod|iPhone|iPad/.test(); isAppleDevice();
37. How to clear all cookies in your browser
const clearAllCookies = () => (';').forEach((c) => ( = (/^ +/, '').replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`)));
38. Check whether the function is an asynchronous function
const isAsyncFunction = (f) => (f) === '[object AsyncFunction]';
39. How to know if a piece of code is running in the browser
const runningInBrowser = typeof window === 'object' && typeof document === 'object';
40. How to know if a piece of code is running in node
const runningInNode= typeof process !== 'undefined' && != null && != null;
41. Detect dark mode
This is a very convenient way to check if the user has dark mode enabled on their browser.
const isDarkMode = && ('(prefers-color-scheme: dark)').matches (isDarkMode)
42. Scroll the element to the top
One single-line method for scrolling elements is the use method.
//Method Oneconst toTop = (element) => ({ behavior: "smooth", block: "start" });
43. Scroll the element to the bottom
const toBottom = (element) => ({ behavior: "smooth", block: "end" });
44.Navigate to the top of the page
This method is used to return to the top of the page.
const goToTop = () => (0, 0); goToTop();
45. Whether to scroll to the bottom of the page
This method is used to determine whether the page is at the bottom.
const scrolledToBottom = () => + >= ;
46. Convert JSON to map
This function allows us to convert Map objects to JSON strings in a simple way.
const jsonToMap = (json) => new Map(((json)));
47. Generate a 128-bit UUID
This function allows us to generate a UUID with a 128-bit value to uniquely identify an object or entity.
const generateUUID = (a) => a ? (a ^ ((() * 16) >> (a / 4))).toString(16) : ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace( /[018]/g, generateUUID);
48. Redirect to a URL
This method is used to redirect to a new URL.
const redirect = url => = url redirect("/")
49. Open the browser print box
This method is used to open the browser's print box.
const showPrintDialog = () => ()
50. Delete all cookies
This method uses access cookies and clears all cookies stored on the web page.
const clearCookies = (';').forEach(cookie => = (/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));
Summarize
This is the end of this article about 50 super useful JavaScript single-line code. For more related JS single-line code content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!