This is the 17th day of my participation in the More text Challenge. For more details, see more text Challenge

What is a single line of code?

  • One-line code is a code practice where we perform some function with just one line of code.

Ternary operator

// Longhand
const age = 18;
let greetings;

if (age < 18) {
  greetings = 'You're not old enough.';
} else {
  greetings = 'You're young! ';
}

// Shorthand
const greetings = age < 18 ? 'You're not old enough.' : 'You're young! ';
Copy the code

Uppercase string

const capitalize = (str) = > str.charAt(0).toUpperCase() + str.slice(1);
console.log(capitalize('hello world'));
// Hello world
Copy the code

Short-circuit assessment shorthand (very common)

  • When assigning a variable value to another variable, you might want to ensure that the source variable is not null, undefined, or empty.

You can write long if statements with multiple conditions, or you can use short-circuit evaluation.

// Longhand
if(name ! = =null|| name ! = =undefined|| name ! = =' ') {
  let fullName = name;
}

// Shorthand
const fullName = name || 'buddy';
Copy the code

Type of detection Equipment

  • Use regular expressions to detect the navigator.userAgent property to determine whether the device is opened on a mobile device or on a desktop/laptop.
const detectDeviceType = () = >/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent) ? 'Mobile' : 'Desktop';
Copy the code

Check if the user is on an Apple device

const isAppleDevice = () = > /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);
// true/false
Copy the code

Check if the user is on an Android device

const isAndroidDevice = () = > /android/.test(navigator.platform);
console.log(isAndroidDevice);
// true/false
Copy the code

Reverse string

const reverse = str= >STR. The split (' '). The reverse () join (', '); The reverse (" hello world ");Copy the code

Truncate the string from the middle

const truncateStringMiddle = (string, length, start, end) = > {
  return `${string.slice(0, start)}.${string.slice(string.length - end)}`;
};

console.log(
  truncateStringMiddle(
    'A long story goes here but then eventually ends! '.// string
    25.// The size of the required string
    13.// Start from the digit of the original string
    17.// Stop the intercept from the original string at the digit));// A long story ... eventually ends!
Copy the code

Truncate the string at the end

const truncateString = (string, length) = > {
  return string.length < length ? string : `${string.slice(0, length - 3)}. `;
};

console.log(
  truncateString('Hi, I should be truncated because I am too loooong! '.36));// Hi, I should be truncated because...
Copy the code

Get the actual type of a variable (common)

const trueTypeOf = (obj) = > {
  return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
};

console.log(trueTypeOf(' '));
// string
console.log(trueTypeOf(0));
// number
console.log(trueTypeOf());
// undefined
console.log(trueTypeOf(null));
// null
console.log(trueTypeOf({}));
// object
console.log(trueTypeOf([]));
// array
console.log(trueTypeOf(0));
// number
console.log(trueTypeOf(() = > {}));
// function
Copy the code

Check whether the variable is an array

const isArray = (arr) = > Array.isArray(arr);

console.log(isArray([1.2.3]));
// true
console.log(isArray({ name: 'Ovi' }));
// false
console.log(isArray('Hello World'));
// false
Copy the code

Get a unique value in an array (array de-duplicate)

const uniqueArr = (arr) = > [...new Set(arr)];

console.log(uniqueArr([1.2.3.1.2.3.4.5]));
// [1, 2, 3, 4, 5]
Copy the code

Deduplicate the array object

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

Different ways to merge multiple arrays

  • There are two ways to merge arrays. One is to use the concat method. Another uses the extension operator (…) .
// Merge but don't remove the duplications
const merge = (a, b) = > a.concat(b);
// Or
const merge = (a, b) = > [...a, ...b];

// Merge and remove the duplications
const merge = [...new Set(a.concat(b))];
// Or
const merge = [...new Set([...a, ...b])];
Copy the code

Copy the text to the clipboard

const copyTextToClipboard = async (text) => {
  await navigator.clipboard.writeText(text);
};
Copy the code

Swap two variables

[foo, bar] = [bar, foo];
Copy the code

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

Randomly generate a six-digit verification code

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

Id card regular pattern

onst 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

Window.location. search turns the JS object

const searchObj = search= > JSON.parse(` {"The ${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'
// So 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

Gets the parameter on the URL, another implementation of the above

 const searchObj = () = > {
   let q = {};
   location.search.replace(/([^?&=]+)=([^&]*)/g.(_,k,v) = >q[k]=v);
   return q;
 }
Copy the code

Converts numbers to thousandths

const toDecimalMark = num= > num.toLocaleString('en-US');
toDecimalMark(25305030399.8790); / / "25305030399879"
Copy the code

Turn a multidimensional array into 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]
Copy the code

Filter object array

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

Convert 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

Cipher combination regularity

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

The browser Developer Tool console selects all the elements $$corresponding to the current page

$$,'a')
// All a elements
Copy the code

Amazing JS code

(! (~ + []) + {}) [- [~ +""] + [] [] * [~ + []] + ~ ~! + + []] + [] ({}) [[~! + []] * ~ + []]//sb
Copy the code