13 lines of JavaScript code make you look like a master

Javascript can do many magical things, and there are many things to learn. Today we will introduce some short and concise code segments.

Gets a random Boolean value (True/False)

Using math Random () will return a random number from 0 to 1, and then judge whether it is greater than 0.5. It will get a value with a 50% probability of True or False

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

Judge whether a date is a working day

Judge whether the given date is a working day

const isWeekday = (date) => date.getDay() % 6 !== 0;
console.log(isWeekday(new Date(2021, 0, 11)));
// Result: true (Monday)
console.log(isWeekday(new Date(2021, 0, 10)));
// Result: false (Sunday)

Reverse string

There are many ways to reverse a string. The simplest one is used here, using split(), reverse(), and join()

const reverse = str => str.split('').reverse().join('');
reverse('hello world');     
// Result: 'dlrow olleh'

Judge whether the current tab is visible

The browser can open many tabs, below 👇🏻 The code snippet is to determine whether the current tab is an active tab

const isBrowserTabInView = () => document.hidden;
isBrowserTabInView();

Judge whether the number is odd or even

The modulo operator% can do this very well

const isEven = num => num % 2 === 0;
console.log(isEven(2));
// Result: true
console.log(isEven(3));
// Result: false

Get time from Date object

Using the Date object The toTimeString() method is converted to a time string, and then the string can be intercepted

const timeFromDate = date => date.toTimeString().slice(0, 8);
console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0))); 
// Result: "17:30:00"
console.log(timeFromDate(new Date()));
// Result: returns the current time

Retain specified decimal places

const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);
// Examples
toFixed(25.198726354, 1);       // 25.1
toFixed(25.198726354, 2);       // 25.19
toFixed(25.198726354, 3);       // 25.198
toFixed(25.198726354, 4);       // 25.1987
toFixed(25.198726354, 5);       // 25.19872
toFixed(25.198726354, 6);       // 25.198726

Checks whether the specified element is in focus

You can use document Activeelement to determine whether the element is in focus

const elementIsInFocus = (el) => (el === document.activeElement);
elementIsInFocus(anyElement)
// Result: returns True if it is in focus state; otherwise, returns False

Check whether the current user supports touch events

const touchSupported = () => {
  ('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch);
}
console.log(touchSupported());
// Result: if the touch event is supported, it will return True; otherwise, it will return False

Check whether the current user is an apple device

You can use navigator Platform determines whether the current user is an apple device

const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);
// Result: Yes, the Apple device will return True

Scroll to the top of the page

window.scrollTo() will scroll to the specified coordinates. If the coordinates are set to (0, 0), it will return to the top of the page

const goToTop = () => window.scrollTo(0, 0);
goToTop();
// Result: will scroll to the top

Gets the average of all parameters

You can use the reduce() function to calculate the average of all parameters

const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4);
// Result: 2.5

Convert Fahrenheit / Celsius

No longer afraid to deal with temperature units. The following two functions are the conversion of two temperature units.

const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32;
const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9;
// Examples
celsiusToFahrenheit(15);    // 59
celsiusToFahrenheit(0);     // 32
celsiusToFahrenheit(-20);   // -4
fahrenheitToCelsius(59);    // 15
fahrenheitToCelsius(32);    // 0

Thank you for reading. I hope you will gain something 😄

Keywords: Javascript Front-end ECMAScript html5

Added by xenophobia on Sun, 19 Dec 2021 00:29:14 +0200