Here, in no particular order, are 30 single lines of JavaScript code THAT I use in development.

1. Enforce a Boolean value

To cast a variable to a Boolean value without changing its value:

const myBoolean = !! myVariable; !!!!! null //false!!!!! undefined //false!!!!!false // false!!!!! ture // ture !!"" // false!!!!!"string" // true!!!!! 0 / /false!!!!! 1 / /true!!!!! {} / /true!!!!! [] / /true
Copy the code

2. Set properties for an object based on a condition

To use the spread operator to conditionally set properties on an object:

const myObject = {... MyProperty && {propName: myPoperty}};let myProperty = 'Jhon'const myObject = {... myProperty && {propName: myProperty}}; // {propName:"Jhon"}
let myProperty = ' 'const myObject = {... myProperty && {propName: myProperty}}; / / {}Copy the code

If the myProperty result is false, && fails and no new property is set; Otherwise, if it is not null, && sets the new property and overrides the original value.

3. Merge objects

const mergedObject = { ... objectOne, ... objectTwo }; const mergedObject = { ... {name:'Jhon', age: '18'}, ...{name1: 'jhon1', age1: '12'}};
// {name: "Jhon", age: "18", name1: "jhon1", age1: "12"} const mergedObject = { ... {name:'Jhon', age: '18'}, ...{name: 'jhon1', age:'12'}};
// {name: "jhon1", age: "12"}
Copy the code

Unrestricted merging is supported, but if the same attribute exists between objects, the latter attribute overrides the previous one. * Please note that this only applies to shallow merges.

4. Swap variables

To swap the values of two variables without using an intermediate variable:

[varA, varB] = [varB, varA];let a = 1;
let b = 2;
[a, b] = [b, a] // a = 2 b = 1
Copy the code

5. Delete Boolean to false

const clean = dirty.filter(Boolean);
const clean = [0, false.true, undefined, null, ' ', 12, 15].filter(Boolean); / / /true, 12, 15]
Copy the code

This will remove values equal to: null, undefined, false, 0 and empty string (” “).

6. Convert element types

To convert the Number element to a String element:

const stringArray = numberArray.map(String);
const stringArray = [1, 2, 3].map(String);
["1"."2"."3"]
Copy the code

If the array contains strings, the strings are left intact. This can also be used to convert String elements to Number:

const numberArray = stringArray.map(Number);
const stringArray = ["1"."2"."3"].map(String); / / [1, 2, 3]Copy the code

7. Format the object as JSON code

To display JSON code in a readable format:

const formatted = JSON.stringify(myObj, null, 4);

const formatted = JSON.stringify({name: 'Jhon', age: 18, address: 'sz'}, null, 4); / * {"name": "Jhon"."age": 18."address": "sz"} * /Copy the code

The stringing command takes three arguments. The first one is a Javascript object. The second is an optional function that can be used to operate on JSON as it is stringed. The last parameter indicates how many Spaces to add as indentation to format the JSON. Omit the last argument, and JSON returns a long line. If there is a circular reference in myObj, the format will fail.

8. Quickly create numeric arrays

To create an array and fill it with numbers, the index is zero:

const numArray = Array.from(new Array(10), (x, i)=> i);
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy the code

9. Randomly generate a six-digit verification code

const code = Math.floor(Math.random() * 1000000).toString().padStart(6, "0"); / / 942377Copy the code

10. Id card regular

const IDReg= /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9 ])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}[0-9Xx]$)/;Copy the code

11. The window. The location. Search the JS object

Sometimes we will change the url query parameters from question mark (?) After the start of the URL (query section) for conversion

const searchObj = search => JSON.parse(`{"${decodeURIComponent(search.substring(1)).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"')}"} `); // If the request URL is //'https://www.baidu.com?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=js&rsv_pq=a86b5e5f0007bceb&rsv_t=1e1fAVan%2BVlnkhJHFB 0BIGLdLM2slszYMJBTTfFkmyyBUzBpw0ggeuVDE50&rqlang=cn&rsv_enter=0&inputT=1287&rsv_sug3=5&rsv_sug1=3&rsv_sug7=101&rsv_sug2= 0&rsv_sug4=1907'// Then window.location.search is:let search = '? ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=js&rsv_pq=a86b5e5f0007bceb&rsv_t=1e1fAVan%2BVlnkhJHFB0BIGLdLM2slszYMJBTTfFkm yyBUzBpw0ggeuVDE50&rqlang=cn&rsv_enter=0&inputT=1287&rsv_sug3=5&rsv_sug1=3&rsv_sug7=101&rsv_sug2=0&rsv_sug4=1907'
searchObj(search)
Copy the code

Formatting the query string yields the following objects:

12. JS object to URL query string

const objectToQueryString = (obj) => Object.keys(obj).map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`).join('&');
objectToQueryString({name: 'Jhon', age: 18, address: 'beijing'})
// name=Jhon&age=18&address=beijing
Copy the code

13. Get array intersection

const similarity = (arr, values) => arr.filter(v => values.includes(v)); similarity([1, 2, 3], [1, 2, 4]); / / [1, 2]Copy the code

14. Check the device type

Use regular expressions to check the navigator.userAgent property to determine whether the device is opened on a mobile device or a desktop/laptop.

const detectDeviceType = () =>/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent) ? 'Mobile' : 'Desktop';
Copy the code

15. Convert numbers into thousandths

const toDecimalMark = num => num.toLocaleString('en-US'); ToDecimalMark (12305030388.9087); //"12305030388909"
Copy the code

Convert multidimensional arrays to one-dimensional arrays

const deepFlatten = arr => [].concat(... arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v))); deepFlatten([1, [2], [[3], 4], 5]); / / [1, 2, 3, 4, 5]Copy the code

17. Filter object arrays

const reducedFilter = (data, keys, fn) =>data.filter(fn).map(el =>keys.reduce((acc, key) => {acc[key] =el[key];returnacc; }, {})); const data = [ { id: 1, name:'john',
    age: 24
  },
  {
    id: 2,
    name: 'mike',
    age: 50
  }
];

let a = reducedFilter(data, ['id'.'name'], item => item.age > 24); // [{ id: 2, name: 'mike'}]
Copy the code

18. Hump string formatting

Converts the hump spelling of a string to a specific format.

Use string.replace () to remove underscores, hyphens, and Spaces, and convert words in the hump spelling format to all lowercase. The second argument separator is omitted and the _ separator is used by default.

const fromCamelCase = (str, separator = '_') =>str.replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2').replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2').toLowerCase();

fromCamelCase('someDatabaseFieldName'.' '); // 'some database field name'
fromCamelCase('someLabelThatNeedsToBeCamelized'.The '-'); // 'some-label-that-needs-to-be-camelized'
fromCamelCase('someJavascriptProperty'.'_'); // 'some_javascript_property'
Copy the code

19. Check whether the IP address is absolute

const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str);

isAbsoluteURL('https://google.com'); // true
isAbsoluteURL('ftp://www.myserver.net'); // true
isAbsoluteURL('/foo/bar'); // false
Copy the code

20. Get the number of days between two dates

const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 * 3600 * 24);
getDaysDiffBetweenDates(new Date('2017-12-13'), new Date('2017-12-22')); / / 9Copy the code

21. Array deduplication

const deDupe = (myArray) => [... new Set(myArray)];
deDupe([1, 1, 2, 1, 3, 3, 4])
// [1, 2, 3, 4]
Copy the code

22. Array objects are deduplicated

const uniqueElementsBy = (arr, fn) =>arr.reduce((acc, v) => {if(! acc.some(x => fn(v, x))) acc.push(v);return acc;}, []);

uniqueElementsBy([{id: 1, name: 'Jhon'}, {id: 2, name: 'sss'}, {id: 1, name: 'Jhon'}], (a, b) => a.id == b.id)
// [{id: 1, name: 'Jhon'}, {id: 2, name: 'sss'}]
Copy the code

23. RGB color to hexadecimal color

const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');

RGBToHex(255, 165, 1); // 'ffa501'
Copy the code

24. Common password combinations are regular

const passwordReg = /(? ! ^(\d+|[a-zA-Z]+|[~!@# $% ^ & *? ] +)$)^[\w~!@#$%^&*?] 8, 20 {} $/;// - Contains 8 to 20 characters and supports any two of the following characters: uppercase and lowercase letters, digits, and symbolsCopy the code

25. Determine whether the DOM element has a className

const  hasClass = (el, className) => new RegExp(`(^|\\s)${className}(\\s|$)`).test(el.className);
Copy the code

References:

30-seconds-of-code