This is the second day of my participation in the November Gwen Challenge. Check out the details: the last Gwen Challenge 2021


Recently in foreign technical community saw some articles about a line of code, feel very interesting, I sorted out a down to share with you, I hope to help you ~

These methods use some APIS to make things easier, but some of them aren’t very elegant to write on a single line, so here’s how to use the API!

First, date processing

1. Check whether the date is valid

This method is used to check whether the given date is valid:

const isDateValid = (. val) = > !Number.isNaN(new Date(... val).valueOf()); isDateValid("December 17, 1995 03:24:00");  // true
Copy the code

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
Copy the code

There are still 90 days to Chinese New Year

3. What day of the year is the date

This method is used to detect the day of the year in which the given date is located:

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

dayOfYear(new Date());   / / 307
Copy the code

More than 300 days have passed since 2021

4. Time formatting

This method can be used to convert time to the hour:minutes:seconds format:

const timeFromDate = date= > date.toTimeString().slice(0.8);
    
timeFromDate(new Date(2021.11.2.12.30.0));  / / 12:30:00
timeFromDate(new Date());  // Return the current time 09:00:00
Copy the code

Second, string processing

1. Capitalize the first letter of the string

This method is used to capitalize the first letter of an English string:

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

capitalize("hello world")  // Hello world
Copy the code

2. Flip the 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'
Copy the code

3. Random string

This method is used to generate a random string:

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

randomString();
Copy the code

4. Truncate the string

This method truncates a string from a 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... '
Copy the code

5. Remove HTML from the string

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

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

Array processing

1. Remove duplicates from the 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]));
Copy the code

2. Check whether the array is empty

This method is used to determine whether an array is empty and returns a Boolean value:

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

isNotEmpty([1.2.3]);  // true
Copy the code

3. Merge two arrays

Two arrays can be merged using the following methods:

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

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

Four, 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); 
Copy the code

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
Copy the code

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);
Copy the code

4. Specify the number of digits to be rounded

This method is used to round a number to the specified number of bits:

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

round(1.005.2) / / 1.01
round(1.555.2) / / 1.56
Copy the code

Five, color operation

1. Convert RGB to 16

This method converts an RGB color value to a hexadecimal value:

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

rgbToHex(255.255.255);  // '#ffffff'
Copy the code

2. Obtain a random hexadecimal color

This method is used to get a random hex color value:

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

randomHex();
Copy the code

Vi. Browser operation

1. Copy the content to the clipboard

The method USES the navigator. Clipboard. WriteText to implement the text copied to the clipboard:

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

copyToClipboard("Hello World");
Copy the code

2. Clear all cookies

This method can access cookies and clear all cookies stored in a web page by using document.cookie:

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

3. Obtain the selected text

This method gets the user-selected text via the built-in getSelection property:

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

getSelectedText();
Copy the code

4. Check whether it is dark mode

This method is used to check whether the current environment is in dark mode. It is a Boolean value:

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

console.log(isDarkMode)
Copy the code

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();
Copy the code

6. Check whether the current TAB is active

This method is used to check whether the current TAB is active:

const isTabInView = () = > !document.hidden; 
Copy the code

7. Check whether the device is an Apple device

This method is used to check whether the current device is an Apple device:

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

isAppleDevice();
Copy the code

8. Check whether to scroll to the bottom of the page

This method is used to determine whether the page is at the bottom:

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

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/")
Copy the code

10. Open the print box of the browser

This method is used to open the browser’s print box:

const showPrintDialog = () = > window.print()
Copy the code

7. Other operations

1. Random Boolean values

This method returns a random Boolean value. Math.random() yields a random number of 0-1, compared to 0.5, with a half chance of getting a true or false value.

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

randomBoolean();
Copy the code

2. Variable exchange

We can swap the values of two variables without applying the third variable:

[foo, bar] = [bar, foo];
Copy the code

3. Obtain the type of the 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
Copy the code

4. The transition between Fahrenheit and Celsius

This method is used to convert between degrees 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
Copy the code

5. Check whether the object is empty

This method is used to check if a JavaScript object is empty:

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

That’s all for today’s article. Click “like” if you think it’s useful!