Learn 10 practical JavaScript code snippets a day, deepen your understanding of JavaScript syntax, accumulate code optimization experience, new content comes, learn to read code is the best way to improve your coding skills. If you find it helpful, check out the rest of the “Learning JavaScript Code in Fragments” column, or leave a comment in the comments section.

1. 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-09-28 console.log(formatDate(Date.now(), "YYYY-MM-DD HH:mm:ss")); / / the 2021-09-28 18:49:29Copy the code

2. Find the array difference set

To find the difference Set of two arrays, you can use the data structure Set to achieve the implementation, see “JavaScript Set Data Operations: Intersection, Difference Set, Intersection, Symmetric Difference Set”. Here’s another way to subtract an array from another array and return the difference, preserving the order of its elements in the resulting list.

const difference = (a, b) => a.filter((item) => b.indexOf(item) < 0); const arrA = [1, 2, 3, 4]; const arrB = [3, 4, 5, 6]; console.log(difference(arrA, arrB)); // // [1, 2]Copy the code

3. Deep search

The code snippet leverages the array Reduce method to retrieve depth values in deeply nested objects, arrays, and maps, accessing values that belong to the object itself or its prototype, such as accessing the length of a string or getting the size of a Map.

const getDeepValue = (dict, path) => { path = Array.isArray(path) ? path : path.split("."); const value = path.reduce( (obj, key) => obj === undefined ? null : obj instanceof Map ? obj.get(key) ?? obj[key] : obj[key], dict ); return value === undefined ? null : value; }; const articlePage = { list: [ { title: "js", keywords: ["js", "reduce"], }, ], }; [1] console.log(getDeepValue(articlePage, "list.0.keywords.1")); // reduceCopy the code

4. Sort object arrays

For an array of objects or a multi-dimensional book order, you might need to sort a key or index, which is a common requirement in a project.

const sortByKey = (obj, key) => { const values = obj instanceof Map ? Array.from(obj.values()) : Object.values(obj); return values.reduce( (keyedObj, value) => ({ ... keyedObj, [value[key]]: value }), {} ); }; Const arrayObjs = [{id: 2, the title: "2"}, {id: 1, the title: "a"}, {id: 3, the title: "three"},]; console.log(sortByKey(arrayObjs, "id")); / * {' 1 ': {id: 1, the title:}' a ', '2' : {id: 2, the title: '2'}, '3' : {id: 3, the title: '3'}} * / const arrays = [[1, 1, 4], [1, 1, 1],]; console.log(sortByKey(arrays, "2")); // {'1': [1, 1, 1], '4': [1, 1, 4]}Copy the code

5. Merge two objects

The code snippet implements merging two objects, but does not deal with deep nesting, leaving the original structure intact and returning a new copy by deeply merging objects and arrays using recursive methods.

const mergeObjects = (a, b) => { if (a === null || typeof a ! == "object") return b ?? {}; if (b === null || typeof b ! == "object") return b ?? {}; const obj = Array.isArray(a) ? [...a] : a; for (const key in b) { if (b.hasOwnProperty(key)) { obj[key] = mergeObjects(obj[key], b[key]); } } return obj; }; const obj1 = { title: "abc", remark: { text: "remark", }, }; const obj2 = { title: "bcd", desc: { info: "test", }, }; console.log(mergeObjects(obj1, obj2)); // { title: 'bcd', remark: { text: 'remark' }, desc: { info: 'test' } }Copy the code

6. Class private domain

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 = (() => { 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

7. Find the shortest length

The snippet will find the shortest length of a word in a given string, taking inspiration from functions such as split(), sort(), and pop().

const findShortLength = (str) => str .split(" ") .sort((a, b) => b.length - a.length) .pop().length; const testString = "A lazy person will find an easy way to do it."; const testString2 = "Finding the best WebGL tool."; console.log(findShortLength(testString)); // 1 console.log(findShortLength(testString2)); / / 3Copy the code

8. Data grouping

For a group of data, use the Reduce method to group the data based on the value of a specific key.

const groupBy = (obj, key) => { const values = obj instanceof Map || obj instanceof Set ? Array.from(obj.values()) : Object.values(obj); return values.reduce((acc, value) => { const groupKey = value[key]; if (! Array.isArray(acc[groupKey])) { acc[groupKey] = [value]; } else { acc[groupKey].push(value); } return acc; }, {}); }; Const arrayBooks = [{title: "War ", category:" history "}, {title: "History ", category:" history "}, {title: "Qin Shihuang ", category:" history "}, {title: "Qin Shihuang ", category: "History"}, {title: "liu bowen," category: "biography"}, {title: "zhang juzheng," category: "biography"},]; console.log(groupBy(arrayBooks, "category")); / * {' history ': [{title:' ce 'category:' history '}, {title: 'history of qin and han dynasties' category:' history '}, {title: 'the emperor', the category: 'history'}], 'biographies: [{title:' liu bowen 'category:' biographies'}, {title: 'zhang juzheng, category:' biographies'}]} * /Copy the code

9. One-time events

The snippet implementation listens for DOM events and performs them only once for bound events.

const onceTrigger = (callback) => { const handler = (e) => { e.currentTarget.removeEventListener(e.type, handler); callback(e); }; return handler; }; const elemSubmit = document.querySelector("button"); elemSubmit.addEventListener( "click", onceTrigger(() => { console.log("click"); }));Copy the code

10. Conditional events

Similar to the one-time event above, conditional events mean that the event will not respond when certain conditions are met, such as the click event will not be launched after the button is clicked three times.

const conditionTrigger = (callback, checkFn) => {
    const handler = (e) => {
        if (checkFn(e)) {
            e.currentTarget.removeEventListener(e.type, handler);
        }
        callback(e);
    };
    return handler;
};

let clickCount = 0;
const elemSubmit = document.querySelector("button");
elemSubmit.addEventListener(
    "click",
    conditionTrigger(
        () => {
            console.log("click");
            clickCount = clickCount + 1;
        },
        () => clickCount > 3
    )
);
Copy 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.