13 JavaScript one-line programs that make you look like an expert

Posted by phpretard on Thu, 23 Dec 2021 01:40:01 +0100

Author: shade
Translator: front end Xiaozhi
Source: medium

There are dreams and dry goods. Wechat search [Daqian world] pays attention to this bowl washing wisdom who is still washing dishes in the early morning.

This article GitHub https://github.com/qq449245884/xiaozhi It has been included. There are complete test sites, materials and my series of articles for the interview of front-line large factories.

JavaScript can do many interesting things, from complex frameworks to processing API s, there are too many things to learn. But it also allows us to do great things in just one line.

1. Obtain a random Boolean value (true/false)

This function uses math The random () method returns a Boolean value (true or false). Math.random creates a random number between 0 and 1. As long as we check whether it is higher or lower than 0.5, we have a 50% chance of getting true or false.

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

2. Check whether the date provided is a working day

Using this method, we can check whether the date provided in the function is a weekday or weekend day.

const isWeekday = (date) => date.getDay() % 6 !== 0;

console.log(isWeekday(new Date(2021, 7, 6)));
// true because it's Friday

console.log(isWeekday(new Date(2021, 7, 7)));
// false because it's Saturday

3. Reverse string

There are several different ways to reverse a string. This is the simplest one, using the split(), reverse() and join() methods.

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

4. Check whether the current label is hidden

Document.hidden (read-only property) returns a Boolean value indicating whether the page is hidden (true) or not (false).

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

Off site: I accidentally found that the countdown of iqiyi's advertisement playing time was only carried out when the current tab was activated. When leaving the current tab, the countdown stopped. Baidu found document Hidden.

document.hidden is h5 a newly added api. There is a compatibility problem when using it.

var hidden
if (typeof document.hidden !== "undefined") {
    hidden = "hidden";
} else if (typeof document.mozHidden !== "undefined") {
    hidden = "mozHidden";
} else if (typeof document.msHidden !== "undefined") {
    hidden = "msHidden";
} else if (typeof document.webkitHidden !== "undefined") {
    hidden = "webkitHidden";
}
console.log("Whether the current page is hidden:" + document[hidden])

5. Check whether a number is even or odd

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

6. Get time from a date

const timeFromDate = date => date.toTimeString().slice(0, 8);

console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0))); 
// "17:30:00"

console.log(timeFromDate(new Date()));
// Print current time

7. Keep n decimal places

const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);
// example
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

8. Check whether any element is currently in focus

We can use document The activeelement property checks whether an element is currently in focus.

const elementIsInFocus = (el) => (el === document.activeElement);
elementIsInFocus(anyElement)
// Returns true if in focus and false if not in focus

9. Check whether the current browser supports touch events

const touchSupported = () => {
  ('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch);
}
console.log(touchSupported());
// If the touch event is supported, it will return true; if not, it will return false.

10. Check whether the current browser is on the Apple device

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

11. Scroll to the top of the page

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

12. Get the average value of the parameter

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

13. Fahrenheit / Celsius conversion

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

~After that, I'm washing the bowl. Let's go!

Original text: https://medium.com/dailyjs/13-javascript-one-liners-thatll-make-you-look-like-a-pro-29a27b6f51cb

communication

There are dreams and dry goods. Wechat search [Daqian world] pays attention to this bowl washing wisdom who is still washing dishes in the early morning.

This article GitHub https://github.com/qq449245884/xiaozhi It has been included. There are complete test sites, materials and my series of articles for the interview of front-line large factories.

Topics: Javascript Front-end Vue