This is the 24th day of my participation in Gwen Challenge. For details, see Gwen Challenge.

JavaScript can handle a lot of things, from complex frameworks to API handling, and there’s a lot to learn. Today I’m going to share 15 simple and possibly common function statements.

1. Number of days between two days

This is a common feature that can be used in almost any requirement involving statistics.

const diffDays = (startDate, endDate) => Math.ceil( Math.abs(new Date(startDate) - new Date(endDate)) / (1000 * 60 * 60 * 24) ); console.log(diffDays("2021-06-01", "2021-06-23")); / / 22Copy the code

Capitalize the first letter

Using this function, you can easily capitalize the first letter of a string.

const capitalize = (strContent) =>
    `${strContent.charAt(0).toUpperCase()}${strContent.slice(1)}`;
console.log(capitalize("devPoint")); // DevPoint
Copy the code

3. Convert the string to a number

To interact with the backend API, the numbers typically entered in the From form are numeric strings that need to be converted to numbers before being submitted to the backend. Using type coercion to convert a string to a number is the most straightforward method.

const toNumber = (str) => +str; // Explicitly converts a string to a Number const toNumber2 = (STR) => Number(STR); console.log(toNumber("100")); // 100 console.log(toNumber2("99")); / / 99Copy the code

4. Convert numbers to strings

const toString = (num) => num + ""; // Explicitly convert a string to a number const toString2 = (num) => num.toString(); Const number = 100.0; console.log(typeof toString(number)); // string console.log(typeof toString2(number)); // stringCopy the code

5. Verify that the array is empty

You can use the isArray method to determine that the array is an array and then check if the length of the array is greater than 0.

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

console.log(isNotEmpty([6, 7, 8])); // true
console.log(isNotEmpty([])); // false
Copy the code

6. Array merge

There are many different ways to merge arrays, such as concat methods, extension operators… . If you need to consider de-weighting, you can consider Set.

const mergeArray = (a, b) => a.concat(b);
const mergeBySpread = (a, b) => [...a, ...b];
const mergeBySet = (a, b) => [...new Set(a.concat(b))];

const arr1 = [6, 7, 8, "b"];
const arr2 = ["a", 7, 8, "b"];

console.log(mergeArray(arr1, arr2)); // [6, 7, 8, 'b','a', 7, 8, 'b']
console.log(mergeBySpread(arr1, arr2)); // [6, 7, 8, 'b','a', 7, 8, 'b']
console.log(mergeBySet(arr1, arr2)); // [ 6, 7, 8, 'b', 'a' ]
Copy the code

7. Array sort

JavaScript’s built-in sorting method is hard to use and doesn’t handle numbers very well, so this function is an easy way to sort an array.

const sort = (arr) => arr.sort((a, b) => a - b); console.log(sort([10, 8, 2, 68, 3])); // [2, 3, 8, 10, 68]Copy the code

8. Generate random hexadecimal colors

Generating RGB colors is a little easier, but creating random hexadecimal colors can be a little more complicated. This function will generate a random hexadecimal color.

const randomColor = () =>
    `#${Math.random().toString(16).slice(2, 8).padStart(6, "0")}`;

const randomColor2 = () => `#${(~~(Math.random() * (1 << 24))).toString(16)}`;

console.log(randomColor()); // #4fd21f
console.log(randomColor2()); // #2c456b
Copy the code

9. Get a Cookie

The front end retrieves the cookie of the current page through document.cookie, then retrieves the cookie value of the top name and returns it.

const getCookie = (name, strCookie) => `; ${strCookie}`.split(`; ${name}=`).pop().split(";" ).shift(); console.log(getCookie("_ga", document.cookie)); / / GA1.2.918318285.1606740576Copy the code

10. Get the text selected by the user

When the user selects text with the cursor, it can be retrieved using the getSelection method on the Window object.

const getSelectedText = () => window.getSelection().toString();
console.log(getSelectedText());
Copy the code

11. Variable value exchange

Sometimes, you need to swap the values of two variables, or as is common in the interview process, how to swap the values of two variables without a third variable. The following code can be done simply:

let a = 1; let b = 2; [a, b] = [b, a]; console.log(a, b); 1 / / 2Copy the code

12. Get the last item of the array

Usually the last item of an array is retrieved by the length of the array. Here’s how the slice method works.

const getLast = (arr) => arr.slice(-1)[0]; const arrTest = [1, 2, 3, 4, 5]; console.log(getLast(arrTest)); / / 5Copy the code

13. Use square brackets to dynamically set the key of the object

Sometimes, when creating an object, you want to change the attribute name of the object based on a specific condition or variable, using square brackets [].

const dynamic = "url";
const item = {
    brand: "DevPoint",
    [dynamic]: "devpoint.cn",
};
console.log(item); // { brand: 'DevPoint', url: 'devpoint.cn' }
Copy the code

14. The use of||Setting defaults

Set default values for variables to avoid exceptions to unprocessed data.

const getTitle = (obj)=>obj.title || "";
Copy the code

15. Shorten the array with length

An easy way to shorten an array is to redefine its length attribute, but this changes the array, meaning that other values in the array will be lost.

const shortenArray = (arr, count) => { arr.length = count; return arr; }; const array = [0, 1, 2, 3, 4, 5, 6, 6, 8, 9]; const shortArr = shortenArray(array, 4); console.log(array); // [ 0, 1, 2, 3 ] console.log(shortArr); // [0, 1, 2, 3] // Const shortenArray = (arr, count) => {const arrTemp = [...arr]; arrTemp.length = count; return arrTemp; }; const array = [0, 1, 2, 3, 4, 5, 6, 6, 8, 9]; const shortArr = shortenArray(array, 4); console.log(array); // [0, 1, 2, 3, 4, 5, 6, 6, 8, 9] console.log(shortArr); // [0, 1, 2, 3]Copy the code