14
Wechat search [Great Relocation to the World], I will share with you the front-end industry trends, learning methods, etc. as soon as possible.
This article GitHub https://github.com/qq449245884/xiaozhi has been included, there are complete test sites, materials and my series of articles for interviews with first-line manufacturers.

Without further ado, let's go directly.

DOM

Check if an element is focused

 const hasFocus = (ele) => ele === document.activeElement

Get all sibling elements of an element

 const siblings = (ele) => 
  .slice.call(ele.parentNode.children).filter((child) => child !== ele);

get selected text

 const getSelectedText = () => window.getSelection().toString();

back to previous page

 history.back();
// Or
history.go(-1);

clear all cookies

 const cookies = document.cookie.split(';').map((item) => 
item.split('=')).reduce((acc, [k, v]) => (acc[k.trim().replace('"', '')] = v) && acc, {});

Convert cookies to objects

 const cookies = document.cookie.split(';').map((item) => item.split('=')).reduce((acc, [k, v]) => (acc[k.trim().replace('"', '')] = v) && acc, {});

array

compare two arrays

 // `a` 和 `b` 都是数组
const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);

// 或者
const isEqual = (a, b) => a.length === b.length && 
  a.every((v, i) => v === b[i]);

// 事例
isEqual([1, 2, 3], [1, 2, 3]); // true
isEqual([1, 2, 3], [1, '2', 3]); // false

Convert an array of objects to a single object

 const toObject = (arr, key) => arr.reduce((a, b) => ({ ...a, [b[key]]: b }), {});
// Or
const toObject = (arr, key) => Object.fromEntries(arr.map((it) => [it[key], it]));

// 事例
toObject([
{ id: '1', name: 'Alpha', gender: 'Male' },
{ id: '2', name: 'Bravo', gender: 'Male' },
{ id: '3', name: 'Charlie', gender: 'Female' }],
'id');
/*
{
'1': { id: '1', name: 'Alpha', gender: 'Male' },
'2': { id: '2', name: 'Bravo', gender: 'Male' },
'3': { id: '3', name: 'Charlie', gender: 'Female' }
}
*/

Count based on properties of an array of objects

 const countBy = (arr, prop) => arr.reduce((prev, curr) => ((prev[curr[prop]] = ++prev[curr[prop]] || 1), prev), {});

// 事例
countBy([
{ branch: 'audi', model: 'q8', year: '2019' },
{ branch: 'audi', model: 'rs7', year: '2020' },
{ branch: 'ford', model: 'mustang', year: '2019' },
{ branch: 'ford', model: 'explorer', year: '2020' },
{ branch: 'bmw', model: 'x7', year: '2020' },
],
'branch');

// { 'audi': 2, 'ford': 2, 'bmw': 1 }

Check if array is empty

 const isNotEmpty = (arr) => Array.isArray(arr) && Object.keys(arr).length > 0;

// 事例
isNotEmpty([]); // false
isNotEmpty([1, 2, 3]); // true

object

Check if multiple objects are equal

 const isEqual = (...objects) => objects.every((obj) =>
  JSON.stringify(obj) === JSON.stringify(objects[0]));
// 事例

console.log(isEqual({ foo: 'bar' }, { foo: 'bar' })); // true
console.log(isEqual({ foo: 'bar' }, { bar: 'foo' })); // false

Extract the value of the specified property from an array of objects

 const pluck = (objs, property) => objs.map((obj) => obj[property]);
// Example
const aa = pluck([
{ name: '小智', age: 20 },
{ name: '大志', age: 25 },
{ name: '王大志', age: 30 },
],
'name');
// [ '小智', '大志', '王大志' ]

Reverse object keys and values

 const invert = (obj) => Object.keys(obj).reduce((res, k) => Object.assign(res, { [obj[k]]: k }), {});
// 或
const invert = (obj) => Object.fromEntries(Object.entries(obj).map(([k, v]) => [v, k]));
// 事例
invert({ a: '1', b: '2', c: '3' }); // { 1: 'a', 2: 'b', 3: 'c' }

Remove all null and undefined properties from the object

 const removeNullUndefined = (obj) => 
  Object.entries(obj)
   .reduce((a, [k, v]) => (v == null ? a : ((a[k] = v), a)), {});

// 或

const removeNullUndefined = (obj) =>
  Object.entries(obj)
  .filter(([_, v]) => v != null)
  .reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {});

// 或

const removeNullUndefined = (obj) => 
    Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));

// 例子
removeNullUndefined({
  foo: null,
  bar: undefined,
  fuzz: 42}
); 
// { fuzz: 42 }

Sort objects based on their properties

 Object.keys(obj)
  .sort()
  .reduce((p, c) => ((p[c] = obj[c]), p), {});

// 事例
const colors = {
  white: '#ffffff',
  black: '#000000',
  red: '#ff0000',
  green: '#008000',
  blue: '#0000ff',
};

sort(colors);

/*
{
  black: '#000000',
  blue: '#0000ff',
  green: '#008000',
  red: '#ff0000',
  white: '#ffffff',
}
*/

Check if an object is a Promise

 const isPromise = (obj) =>
!!obj && (typeof obj === 'object' || typeof obj === 'function') && 
typeof obj.then === 'function';

Check if an object is an array

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

string

Check if path is relative

 const isRelative = (path) => !/^([a-z]+:)?[\\/]/i.test(path);

// 例子
isRelative('/foo/bar/baz'); // false
isRelative('C:\\foo\\bar\\baz'); // false
isRelative('foo/bar/baz.txt'); // true
isRelative('foo.md'); // true

Change the first character of a string to lowercase

 const lowercaseFirst = (str) => `${str.charAt(0).toLowerCase()}${str.slice(1)}`;

// 例子
lowercaseFirst('Hello World'); // 'hello World'

repeat a string

 const repeat = (str, numberOfTimes) => str.repeat(numberOfTimes);

// 例子
repeat('ab', 3)
// ababab

Dates

Add "am/pm" suffix to an hour

 // `h` is an hour number between 0 and 23
const suffixAmPm = (h) => `${h % 12 === 0 ? 12 : h % 12}${h < 12 ? 'am' : 'pm'}`;

// 例子
suffixAmPm(0); // '12am'
suffixAmPm(5); // '5am'
suffixAmPm(12); // '12pm'
suffixAmPm(15); // '3pm'
suffixAmPm(23); // '11pm'

Calculate the number of days between two dates

 const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));

// 例子
diffDays(new Date('2014-12-19'), new Date('2020-01-01')); // 1839

Check if date is valid

 const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());

isDateValid("December 17, 1995 03:24:00"); // true

other

Check if code is running in Node.js

 const isNode = typeof process !== 'undefined' && process.versions != null && 
  process.versions.node != null;

Check if the code is running in the browser

 const isBrowser = typeof window === 'object' && typeof document === 'object';

Convert URL parameters to objects

 const getUrlParams = (query) =>Array.from(new   URLSearchParams(query)).reduce((p, [k, v]) => Object.assign({}, p, { [k]: p[k]   ? (Array.isArray(p[k]) ? p[k] : [p[k]]).concat(v) : v }),{});

// 例子
getUrlParams(location.search); // Get the parameters of the current URL
getUrlParams('foo=Foo&bar=Bar'); // { foo: "Foo", bar: "Bar" }

// Duplicate key
getUrlParams('foo=Foo&foo=Fuzz&bar=Bar'); // { foo: ["Foo", "Fuzz"], bar: "Bar" }

Dark detection mode

 const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;

copy to clipboard

 const copyToClipboard = (text) => 
  navigator.clipboard.writeText(text);

// 例子
copyToClipboard("Hello World");

Convert RGB to Hex

 const rgbToHex = (r, g, b) =>
   "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);

// 例子
rgbToHex(0, 51, 255); // #0033ff

Generate a random hex color

 const randomColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`;

// 或者

const randomColor = () => `#${(~~(Math.random() * (1 << 24))).toString(16)}`;

Generate random IP address

 const randomIp = () => Array(4).fill(0)
.map((_, i) => Math.floor(Math.random() * 255) + (i === 0 ? 1 : 0))
.join('.');

// 例子
randomIp(); // 175.89.174.131

Generate random strings using Node crypto module

 const randomStr = () => require('crypto').randomBytes(32).toString('hex');

~~End, I'm Shawanzhi, I'm going to have a drip, see you in the next issue!


The bugs that may exist after the code is deployed cannot be known in real time. In order to solve these bugs afterwards, a lot of time is spent on log debugging. By the way, I recommend a useful bug monitoring tool , Fundebug .

Author: Ahmad Translator: Front-end Xiaozhi Source: ishadee

original:

https://javascript.plainenglish.io/17-life-saving-javascript-one-liners-part1-b0b0b32c9f61
https://javascript.plainenglish.io/another-17-life-saving-javascript-one-liners-8c335bf73d2c

comminicate

If you have dreams and dry goods, you can search for [Great Move to the World] on WeChat and pay attention to this Shawanzhi who is still washing dishes in the early hours of the morning.

This article GitHub https://github.com/qq449245884/xiaozhi has been included, there are complete test sites, materials and my series of articles for interviews with first-line manufacturers.


王大冶
68.1k 声望105k 粉丝