Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Short step, no thousands of miles; Not small streams, beyond into rivers and seas. Steed leap, not ten steps; Inferior horse ten riding, gongnever give up. Stop chipping halfway, deadwood can’t be broken; Constant dripping wears away the stone.

Find the day of the year on which a date is located

There is always a demand for dates. Today, this demand refreshed my little brain again and FINALLY found a suitable solution:

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

yearNum(new Date());
Copy the code

Calculate the number of days between two dates

Another one about dates:

const dayDistance = (date1, date2) = > Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)
    
dayDistance(new Date("2021-10-21"), new Date("2021-10-31"))
Copy the code

The first letter of an English string is automatically capitalized

const capitalize = str= > str.charAt(0).toUpperCase() + str.slice(1)
    
capitalize("hello, world")
Copy the code

Gets the value of the browser Cookie

Document. Cookie to find the cookie value

const cookie = name= > `; The ${document.cookie}`.split(`; ${name}= `).pop().split('; ').shift();
Copy the code

Clear all cookies

We can use document.cookie to access cookies and clear them when we need to clear all cookies stored in the web page:

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

Generates random hexadecimal colors

Math.random and padEnd properties can generate random hexadecimal colors

const color = () = > ` #The ${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6."0")}`;
    
 console.log(color());
Copy the code

Array to heavy

The same old question

const arrSingle = (arr) = > [...new Set(arr)];
    
console.log(arrSingle([1.2.2.2.4.4.5.5.6]));
Copy the code

H5 Address query parameters

const getParams = Object.fromEntries(new URLSearchParams(window.location.search))
Copy the code

Average the numbers

const average = (... args) => args.reduce((a, b) => a + b) / args.length; average(1, 2, 3, 4, 5, 6);Copy the code

Back to the top

const goTop = () = > window.scrollTo(0.0);
    
goTop();
Copy the code

Check if the array is empty

const isEmpty = arr= > Array.isArray(arr) && arr.length > 0;
    
isEmpty([1.2.3]); // true
isEmpty([]); // false
Copy the code

Check whether the user’s device is in dark mode

const isDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
    
console.log(isDark) 
Copy the code