“This is the third day of my participation in the November Gwen Challenge. See details of the event: The last Gwen Challenge 2021”.

In the past, I have summarized some code fragments which are helpful for the efficiency and skills of project development. On the one hand, I have deepened my understanding of Javascript syntax, and on the other hand, I have archived the code. This article is a good summary of the column “Learning Javascript Code in Fragments.”

A practical method

1. localStorage

LocalStorage is one of the local persistent storage methods in HTML5, and also one of the localStorage schemes commonly used in front-end projects. Data stored in localStorage is permanently stored as long as the user does not delete it actively. The value can only be string and cannot be accessed across browsers or domain names. The storage size is generally about 5M. Modern front-end projects basically use localStorage. The following code snippet encapsulates the storage, acquisition and clearing of localStorage data.

const useStorage = (storageKey = "authorization") => { const localKey = `devpoint.local.${storageKey}`; const toJson = (str) => { try { return JSON.parse(str); } catch { return false; }}; const save = (data) => { window.localStorage.setItem(localKey, JSON.stringify(data)); }; const get = () => { const localData = window.localStorage.getItem(localKey); if (localData && localData ! == "") { return toJson(localData); } else { return false; }}; / * * * remove localStorage * / const clear () = = > {window. LocalStorage. SetItem (localKey, ""); }; Return {save, get, clear,}; }; const storageAuth = useStorage(); const loginInfo = { username: "hballard", age: 30, }; storageAuth.save(loginInfo); console.log(storageAuth.get());Copy the code

2. Determine the JSON format

The following code snippet will come in handy when you need to see if the data is in JSON format:

function isJSON(str) {
    try {
        JSON.parse(str);
    } catch {
        return false;
    }
    return true;
}
const data1 = "JavaScript";
const data2 = `{"title":"js"}`;
console.log(isJSON(data1)); // false
console.log(isJSON(data2)); // true
Copy the code

3. Turn the CSV Array

CSV is a widely used spreadsheet today, and you can convert an array to CSV format using a simple code snippet like this:

const arrayToCSV = (array, delimiter = ",") => array .map((item) => item.map((value) => `"${value}"`).join(delimiter)) .join("\n"); const users = [ { name: "hballard", age: 30 }, { name: "sguzman", age: 24 }, { name: "jrowe", age: 28 }, { name: "plowe", age: 32 }, ]; const arrayUsers = users.map((item) => Object.values(item)); console.log(arrayUsers); // [ // [ 'hballard', 30 ], // [ 'sguzman', 24 ], // [ 'jrowe', 28 ], // [ 'plowe', 32 ] // ] const strCsv1 = arrayToCSV(arrayUsers); const strCsv2 = arrayToCSV(arrayUsers, ";" ); console.log(strCsv1); // "hballard","30" // "sguzman","24" // "jrowe","28" // "plowe","32" console.log(strCsv2); // "hballard";" 30" // "sguzman";" 24" // "jrowe";" 28" // "plowe";" 32"Copy the code

4. Judge the number format

The following code snippet shows how to check if a value or variable contains a number (integer, floating point, and so on).

function isNumber(n) { return ! isNaN(parseFloat(n)) && isFinite(n); } console.log(isNumber(100)); / / true on the console. The log (isNumber (3.14)); / / true on the console. The log (isNumber (" 3.14 ")); / / true on the console. The log (isNumber (" a3.14 ")); // false console.log(isNumber("JavaScript")); // falseCopy the code

5. Data type judgment

Data type determination is used in most projects, especially JavaScript, where different methods are used for different data types.

const isCheck = (type, val) => ! [undefined, null].includes(val) && val.constructor === type; console.log(isCheck(Array, ["a"])); // true console.log(isCheck(Object, {})); // true console.log(isCheck(ArrayBuffer, new ArrayBuffer())); // true console.log(isCheck(Boolean, new Boolean(true))); // true console.log(isCheck(RegExp, /./g)); // true console.log(isCheck(Number, 0)); // trueCopy the code

6. Array summation and average

The reduce method executes the provided callback function iterator on each element of the array. It passes in the return value evaluated by the previous element, and the result is a single value, which is the result of running the iterator on all the elements of the array. Useful for array summation, averages, etc.

Array sum
const sum = (... array) => [...array].reduce((acc, current) => acc + current, 0); const testArray = [1, 2, 3, 4, 5]; console.log(sum(1, 2, 3, 4, 5)); // 15 console.log(sum(... testArray)); / / 15Copy the code
The average
const average = (... numbers) => numbers.reduce((acc, current) => acc + current, 0) / numbers.length; const testArray1 = [1, 2, 3, 4, 5]; console.log(average(... testArray1)); // 3 console.log(average(1, 2, 3, 4, 5)); / / 3Copy the code

7. The function chain

Function chain, should be regarded as the code organization form, here put in the code fragment, hoping to have certain inspiration for the project code organization.

function CusModal() { const This = this; this.options = { theme: "default", title: "modal", visible: false, }; const setOptions = function (key, value) { This.options[key] = value; }; this.setTheme = function (theme) { setOptions("theme", theme); return this; }; this.setTitle = function (title) { setOptions("title", title); return this; }; this.show = function () { setOptions("visible", true); }; this.close = function () { setOptions("visible", false); }; this.getOptions = function () { return this.options; }; } const modalHelper = new CusModal(); Modalhelper.settheme ("dark").setTitle(" Publish article window ").show(); console.log(modalHelper.getOptions()); // {theme: 'dark', title: 'Publish article window ', visible: true}Copy the code

8. Complete display of scientific count

In the project, I encountered that the API returned numbers in the way of scientific counting, and the complete numbers needed to be displayed on the page. Usually, it was not clear how many decimal places the numbers of scientific counting were, so the accuracy was not fixed. The following code implements a three digit number greater than 0 after the decimal point, as follows:

function flatNumber(num) { const strNumber = num.toFixed(30); console.log(strNumber); const arrayNumbers = [...strNumber]; const numberIndex = arrayNumbers.findIndex( (item) => parseInt(item, 10) > 0 ); const precision = numberIndex >= 0 ? numberIndex + 1 : 0; return num.toFixed(precision); } const number = 1.71604938271605e-8; console.log(number.toFixed(30)); / / 0.000000017160493827160499945830 console. The log (flatNumber (number)); / / 0.0000000172Copy the code

9. The timer

Timer, in the process of project development results, the use of timer need to strictly control the start and close timer, to avoid too many timer not closed memory leakage, the following code realizes a timer start and stop:

class Timer { constructor(fn, delay) { this._triggerTimer = null; this._delay = delay; this._fn = fn; } stop() { if (this._triggerTimer) { clearTimeout(this._triggerTimer); this._triggerTimer = null; } } begin() { this.stop(); this._triggerTimer = setTimeout(() => { this._fn(); }, this._delay); } // let timerCount = 0; const timerHelper = new Timer(() => { timerCount++; if (timerCount < 5) { console.log(timerCount); timerHelper.begin(); } else { timerHelper.stop(); }}, 2000); timerHelper.begin();Copy the code

10. Time formatting

There are many time-dependent scripting libraries in JavaScript, such as Moment and Luxon, that provide rich time-dependent methods. Here’s how to implement the native methods.

const formatDate = (date, formatStr = "YYYY-MM-DD") => { date = new Date(date); const padStart = (str) => str.toString().padStart(2, "0"); const month = date.getMonth() + 1; const year = date.getFullYear(); const day = date.getDate(); const hours = date.getHours(); const minutes = date.getMinutes(); const seconds = date.getSeconds(); return formatStr .replace(/\bYYYY\b/g, year) .replace(/\bYY\b/g, `${year}`.substring(2)) .replace(/\bMM\b/g, padStart(month)) .replace(/\bM\b/g, month) .replace(/\bDD\b/g, padStart(day)) .replace(/\bD\b/g, day) .replace(/\bHH\b/g, padStart(hours)) .replace(/\bhh\b/g, hours) .replace(/\bmm\b/g, padStart(minutes)) .replace(/\bss\b/g, padStart(seconds)); }; console.log(formatDate(Date.now())); // 2021-11-03 console.log(formatDate(Date.now(), "YYYY-MM-DD HH:mm:ss")); / / the 2021-11-03 18:49:29Copy the code

11. Private methods

JavaScript has its own way to create class private members, but it is currently in an ES2020 pilot draft and has an odd syntax prefixed with #. The following code snippet uses closures, scopes to implement the private domain of a class.

Const Helper = (() => {// Define private method defaultValue const defaultValue = (val, defVal) => {if (val && val! == "") { return val; } else { return defVal; }}; const apiEndpoint = "/Auth"; Class Utility {constructor() {this.loginPath = '${apiEndpoint}/login'; } getVal(key, defVal) { return defaultValue(key, defVal); } } return Utility; }) (); const testHelper = new Helper(); console.log(testHelper.getVal(undefined, 0)); // 0 console.log(testHelper.loginPath); // /Auth/loginCopy the code

12. Null value judgment

As mentioned above, determining null values can be interpreted differently in different projects, and the following code snippet can determine all types of null values.

const isEmpty = (x) => { if (Array.isArray(x) || typeof x === "string" || x instanceof String) { return x.length === 0; } if (x instanceof Map || x instanceof Set) { return x.size === 0; } if ({}.toString.call(x) === "[object Object]") { return Object.keys(x).length === 0; } if (! isNaN(parseFloat(x)) && isFinite(x)) { return false; } return ! x; }; console.log(isEmpty(null)); // true console.log(isEmpty(undefined)); // true console.log(isEmpty([])); // true console.log(isEmpty({})); // true console.log(isEmpty("")); // true console.log(isEmpty(new Set())); // true console.log(isEmpty(0));Copy the code

Code neatness Tips

In project development, in addition to the completion of the corresponding function needs, it is also necessary to re-read the code, to explore the code clean way, code optimization is a work without standard answers, but there are some recommended ways. Here are some tips for clean code. Here are two great sites to learn some code: 1loc.dev/ and 30SecondsofCode.

1. Short cycle

Did you know that in JavaScript you can shorten loops in a single line? This means you can write less code for loops.

const provinces = ["Guangdong", "Jiangxi", "Hunan", "Fujian"];
// 常规
for (let i = 0, len = provinces.length; i < len; i++) {
    console.log(provinces[i]);
}
// 短循环
for (const province of provinces) console.log(province);
Copy the code

2. The array length is changed

In JavaScript, you can resize an array by using the length method, which is used not only to get the length of the array, but also to slice the array.

const array1 = [1, 2, 3, 4, 5, 6];
const array2 = ["Python", "JavaScript", "C++", "Dart"];
array1.length = 3;
array2.length = 1;
console.log(array1); // [1, 2, 3]
console.log(array2); // ["Python"]
Copy the code

3. Convert floating point numbers to integers

To convert floating point numbers to integers, you can usually use the math.floor (), math.round (), and math.ceil () methods. Here’s a short way, bitwise OR, as follows:

/ / regular console. The log (math.h floor (3.14)); / / 3 / / short console. The log (3.14 | 0); / / 3Copy the code

4. Array deduplication

See “Set Data Manipulation in JavaScript: Intersection, Difference, Intersection, And Symmetric Difference sets” for more on the use of sets by leveraging the JavaScript data type Set feature. Use Set to quickly implement array de-duplication as follows:

const removeDupli = (arr) => [...new Set(arr)]; console.log(removeDupli([2, 2, 2, 11, 3])); // [ 2, 11, 3 ] console.log(removeDupli([2, 0, 2, 1, 11, 1])); // [2, 0, 1, 11]Copy the code

5. Array merge

This code merges two arrays into one, which is a quick and easy way to do it without using a loop.

const lang1 = ["JavaScript", "Python", "C++"];
const lang2 = ["C#", "Dart", "Clojure"];
const merge = [...lang1, ...lang2];
console.log(merge); // [ 'JavaScript', 'Python', 'C++', 'C#', 'Dart', 'Clojure' ]
Copy the code

This is the extension operator… The more classical use method of. For more information on the use of extension operators, see 8 Uses of extension Operators in ES6.

6. Get the last item of the array

The shortest way to get the last element of an array is to use the slice method, which simply takes a negative number as an argument and slices the array starting with the last index.

const array = [1, 3, 4, 5, 6, 9, 10, 12]; console.log(array.slice(-1)); // [12] console.log(array.slice(-2)); // [10, 12] console.log(array.slice(-4)); // [6, 9,10, 12]Copy the code

7. Merge objects

Merge multiple objects into one. In JavaScript, you can use… Method, which is also the simplest way to implement this requirement, as follows:

Const article1 = {title: "JavaScript ", lang: "js"}; const article2 = { view: 10, time: "2021", lang: "javascript" }; const article = { ... article1, ... article2, }; console.log(article); // {title: 'JavaScript feature ', lang: 'JavaScript ', view: 10, time: '2021'}Copy the code

If they have the same attributes, the last one overwrites the previous one.

8. Maximum number and minimum number of arrays

This is one of the ways to find the largest or smallest number in an array. It can also be done through a loop. Here is a simple way to do this:

const findMax = (arrayNumbers) => Math.max(... arrayNumbers); const findMin = (arrayNumbers) => Math.min(... arrayNumbers); const arrNumbers = [10, 13, 1, 48, 6, 216]; console.log(findMax(arrNumbers)); // 216 console.log(findMin(arrNumbers)); / / 1Copy the code

conclusion

The flexibility of JavaScript makes programming tricky. As a JavaScript developer, you need to feel like a magician and use your skills wisely and flexibly to improve your ability to organize your code.