Development of conventional single line of code 25 JavaScript

Development of conventional single line of code 25 JavaScript

Here I will introduce my favorite in the development of 30 single line of JavaScript code that, in no particular order.

1. Force Boolean value

To cast to a Boolean variable without changing its value:

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

2. Set the properties for an object based on a condition

To conditionally set properties on an object using spread operator:

const myObject = {... myProperty && {propName:myPoperty}};

let myProperty = 'Jhon'
const myObject = {...myProperty && {propName: myProperty}}; // {propName: "Jhon"}
let myProperty = ''
const myObject = {...myProperty && {propName: myProperty}}; // {}

If myProperty result is false, the && fail and do not set up a new property; otherwise, if you do not, && will set up a new property is empty and overwrite 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"}

Supports unlimited combined, but if the same attribute is present among the object, the front cover behind the property attributes. * Please note that this only applies to shallow consolidation.

4. Variable exchange

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

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

5. Delete the Boolean value is false

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

This will remove equals: null, undefined, false, 0 and an empty string ( '').

6. conversion element type

To Number of elements to a String elements:

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

If the array contains the string, the string left as it is. This can also be used to convert the String elements Number Type:

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

7. JSON format object code that

JSON to display the 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"
}
*/

This command has three parameters of the string. The first is a Javascript object. The second is an optional function that can be used to perform operations when the string of JSON. The last parameter indicates how much space you want to add as an indent to format JSON. The last parameter is omitted, JSON returns a long line. If there is a circular reference myObj, the format will fail.

8. quickly create an array of numbers

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]

9. randomly generated six-digit codes

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

10. Regular ID cards

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]$)/;

11.window.location.search turn JS objects

URL beginning (query part) Sometimes we have to convert the url query parameters that is, from the question mark (?) After

const searchObj = search => JSON.parse(`{"${decodeURIComponent(search.substring(1)).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"')}"}`);

// 假如请求url为
// '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%2BVlnkhJHFB0BIGLdLM2slszYMJBTTfFkmyyBUzBpw0ggeuVDE50&rqlang=cn&rsv_enter=0&inputT=1287&rsv_sug3=5&rsv_sug1=3&rsv_sug7=101&rsv_sug2=0&rsv_sug4=1907'
// 那么 window.location.search 就为:
let search = '?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=js&rsv_pq=a86b5e5f0007bceb&rsv_t=1e1fAVan%2BVlnkhJHFB0BIGLdLM2slszYMJBTTfFkmyyBUzBpw0ggeuVDE50&rqlang=cn&rsv_enter=0&inputT=1287&rsv_sug3=5&rsv_sug1=3&rsv_sug7=101&rsv_sug2=0&rsv_sug4=1907'
searchObj(search)

Formatting the query string to obtain the following objects:

12. JS objects go query string url

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

13. Gets an array of intersection

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

14. The detecting device type

Using regular expressions to detect navigator.userAgent attribute determining device is a mobile device or turns in desktop / laptop PCs.

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

15. converted to digital format thousandth

const toDecimalMark = num => num.toLocaleString('en-US');
toDecimalMark(12305030388.9087); // "12,305,030,388.909"

16 multi-dimensional array to a one-dimensional array

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

17. A filter array of objects

const reducedFilter = (data, keys, fn) =>data.filter(fn).map(el =>keys.reduce((acc, key) => {acc[key] =el[key];return acc;}, {}));
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'}]

18. The hump word string formatted

String conversion hump spelling of a particular format.

Use String.replace () to remove underscores, hyphens and spaces, and converts the format hump spelled word is all lowercase. The second parameter separator is omitted, default _ delimiter.

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', '-'); // 'some-label-that-needs-to-be-camelized'
fromCamelCase('someJavascriptProperty', '_'); // 'some_javascript_property'

19. whether the absolute address

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

20. Get the number of days difference between two dates

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

21. Array deduplication

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

22. The array of objects to heavy

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'}]

23. RGB color hexadecimal color transfer

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

RGBToHex(255, 165, 1); // 'ffa501'

24. Common password combination canonical

const passwordReg = /(?!^(\d+|[a-zA-Z]+|[~!@#$%^&*?]+)$)^[\w~!@#$%^&*?]{8,20}$/;
// -长度8~20位字符,支持大小写字母、数字、符号三种字符中任意两种字符的组合

25. Analyzing dom element has a className

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

Finally, I recommend a push in the front-end learning exchange group 685 910 553 Advanced ( front-end information-sharing ), no matter which direction you are on Earth,
whether you are welcome to work in a few years you settled in! (Within the group regularly offer free collection of some of the main group of free learning materials and books tidied face questions and answers document!)

If you have any objection to this article, then please write your comments in the article comments at.

If you find this article interesting, please share and forward, or you can look at, you acknowledge and encouragement of our articles.

Wish everyone in the programming this road, farther and farther.

Guess you like

Origin blog.csdn.net/tianduantoutiao/article/details/92429359