A very practical JavaScript line of code (sorting and summarizing)

1. Date processing

1. Check if the date is valid
This method is used to check if the given date is valid:

const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());

isDateValid("December 17, 1995 03:24:00");  // true

2. Calculate the interval between two dates
This method is used to calculate the interval between two dates:

const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)
    
dayDif(new Date("2021-11-3"), new Date("2022-2-1"))  // 90

90 days until Chinese New Year~

3. Find the day of the year in which the date falls
This method is used to detect the day of the year in which the given date falls:

const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);

dayOfYear(new Date());   // 307

More than 300 days have passed in 2021~

4. Time formatting
This method can be used to convert time into the format of hours:minutes:seconds:

const timeFromDate = date => date.toTimeString().slice(0, 8);
    
timeFromDate(new Date(2021, 11, 2, 12, 30, 0));  // 12:30:00
timeFromDate(new Date());  // 返回当前时间 09:00:00

Two, string processing

1. Capitalize the first letter of the string
This method is used to capitalize the first letter of the English string:

const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)

capitalize("hello world")  // Hello world

2. Flip String
This method is used to flip a string and return the flipped string:

const reverse = str => str.split('').reverse().join('');

reverse('hello world');   // 'dlrow olleh'

3. Random string
This method is used to generate a random string:

const randomString = () => Math.random().toString(36).slice(2);

randomString();

4. Truncate the string
This method can truncate the string from the specified length:

const truncateString = (string, length) => string.length < length ? string : `${
      
      string.slice(0, length - 3)}...`;

truncateString('Hi, I should be truncated because I am too loooong!', 36)   // 'Hi, I should be truncated because...'

5. Remove HTML from a string
This method is used to remove HTML elements from a string:

const stripHtml = html => (new DOMParser().parseFromString(html, 'text/html')).body.textContent || '';

3. Array processing

1. Remove duplicates from an array
This method is used to remove duplicates from an array:

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

console.log(removeDuplicates([1, 2, 2, 3, 3, 4, 4, 5, 5, 6]));

2. Determine whether an array is empty
This method is used to determine whether an array is an empty array, and it will return a boolean value:

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

isNotEmpty([1, 2, 3]);  // true

3. Merge two arrays
You can use the following two methods to merge two arrays:

const merge = (a, b) => a.concat(b);

const merge = (a, b) => [...a, ...b];

4. Digital operation

1. Determine whether a number is odd or even
This method is used to determine whether a number is odd or even:

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

isEven(996); 

2. Get the average of a set of numbers

const average = (...args) => args.reduce((a, b) => a + b) / args.length;

average(1, 2, 3, 4, 5);   // 3

3. Get a random integer between two integers
This method is used to get a random integer between two integers

const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);

random(1, 50);

4. Rounding to specified digits
This method is used to round a number to specified digits:

const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d)

round(1.005, 2) //1.01
round(1.555, 2) //1.56

Five, color operation

1. Convert RGB to hexadecimal mechanism
This method can convert an RGB color value into a hexadecimal value:

const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);

rgbToHex(255, 255, 255);  // '#ffffff'

2. Obtain a random hexadecimal color
This method is used to obtain a random hexadecimal color value:

const randomHex = () => `#${
      
      Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;

randomHex();

6. Browser Operation

1. Copy content to the clipboard
This method uses
navigator.clipboard.writeText to copy text to the clipboard:

const copyToClipboard = (text) => navigator.clipboard.writeText(text);

copyToClipboard("Hello World");

2. Clear all cookies
This method can use document.cookie to access cookies and clear all cookies stored in the web page:

const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${
      
      new Date(0).toUTCString()};path=/`));

3. Get the selected text
This method gets the text selected by the user through the built-in getSelection property:

const getSelectedText = () => window.getSelection().toString();

getSelectedText();

4. Detect whether it is dark mode
This method is used to detect whether the current environment is dark mode, it is a boolean value:

const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches

console.log(isDarkMode)

5. Scroll to the top of the page
This method is used to return to the top of the page:

const goToTop = () => window.scrollTo(0, 0);

goToTop();

6. Determine whether the current tab is activated
This method is used to detect whether the current tab is activated:

const isTabInView = () => !document.hidden; 

7. Determine whether the current device is an Apple device
This method is used to detect whether the current device is an Apple device:

const isAppleDevice = () => /Mac|iPod|iPhone|iPad/.test(navigator.platform);

isAppleDevice();

8. Whether to scroll to the bottom of the page
This method is used to judge whether the page has reached the bottom:

const scrolledToBottom = () => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight;

9. Redirect to a URL
This method is used to redirect to a new URL:

const redirect = url => location.href = url

redirect("https://www.google.com/")

10. Open the print box of the browser
This method is used to open the print box of the browser:

const showPrintDialog = () => window.print()

7. Other operations

1. Random Boolean value
This method can return a random Boolean value. Use Math.random() to obtain a random number of 0-1. Compared with 0.5, there is a half probability of obtaining a true value or a false value.

const randomBoolean = () => Math.random() >= 0.5;

randomBoolean();

2. Variable exchange
The following forms can be used to exchange the values ​​of two variables without the use of a third variable:

[foo, bar] = [bar, foo];

3. Get the type of variable
This method is used to get the type of a variable:

const trueTypeOf = (obj) => Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();

trueTypeOf('');     // string
trueTypeOf(0);      // number
trueTypeOf();       // undefined
trueTypeOf(null);   // null
trueTypeOf({
    
    });     // object
trueTypeOf([]);     // array
trueTypeOf(0);      // number
trueTypeOf(() => {
    
    });  // function

4. Conversion between Fahrenheit and Celsius
This method is used for conversion between Celsius and Fahrenheit:

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

celsiusToFahrenheit(15);    // 59
celsiusToFahrenheit(0);     // 32
celsiusToFahrenheit(-20);   // -4
fahrenheitToCelsius(59);    // 15
fahrenheitToCelsius(32);    // 0

5. Check whether the object is empty
This method is used to check whether a JavaScript object is empty:

const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;

Guess you like

Origin blog.csdn.net/weixin_43025151/article/details/130111877