This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

Ahmad Translator: Front-end tips source: Ishadee

Have a dream, have dry goods, wechat search [big Move the world] pay attention to this in the early morning is still in the bowl washing wisdom.

In this paper, making github.com/qq449245884… Has been included, a line of large factory interview complete test sites, information and my series of articles.

Let’s cut to the chase.

DOM

Checks if an element is focused

const hasFocus = (ele) => ele === document.activeElement
Copy the code

Gets all siblings of an element

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

Get selected text

const getSelectedText = () => window.getSelection().toString();
Copy the code

Go back to the previous page

history.back();
// Or
history.go(-1);
Copy the code

Clear all Cookies

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

Convert cookies to objects

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

An array of

Comparing two arrays

// both 'a' and 'b' are arrays const isEqual = (a, b) => json.stringify (a) === json.stringify (b); / / or const isEqual = (a, b) = > a. ength = = = b.l ength && a.e very ((v, I) = = = = > v b [I]); // isEqual([1, 2, 3], [1, 2, 3]); // true isEqual([1, 2, 3], [1, '2', 3]); // falseCopy the code

Converts 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])); / / examples/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' } } */Copy the code

Counts based on the properties of the object array

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 }Copy the code

Check if the array is empty

const isNotEmpty = (arr) => Array.isArray(arr) && Object.keys(arr).length > 0; / / examples/isNotEmpty ([]); // false isNotEmpty([1, 2, 3]); // trueCopy the code

object

Checks whether multiple objects are equal

const isEqual = (... objects) => objects.every((obj) => JSON.stringify(obj) === JSON.stringify(objects[0])); / / examples/console log (isEqual ({foo: 'bar'}, {foo: 'bar'})); // true console.log(isEqual({ foo: 'bar' }, { bar: 'foo' })); // falseCopy the code

Retrieves 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: 'sizz ', age: 20}, {name:' sizz ', age: 25}, {name: 'Sizz ', age: 30},],' pluck '); // [' xiaozhi ', 'Dazhi ',' Wang Dazhi ']Copy the code

Inverts the key and value of an object

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' }Copy the code

Removes all null and undefined attributes 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 }Copy the code

Sort objects by their attributes

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', } */Copy the code

Check if an object is a Promise

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

Checks if an object is an array

  const isArray = (obj) => Array.isArray(obj);
Copy the code

string

Check whether the path is relative

const isRelative = (path) => ! /^([a-z]+:)? [\\/]/i.test(path); / / example isRelative ('/foo/bar/baz '); // false isRelative('C:\\foo\\bar\\baz'); // false isRelative('foo/bar/baz.txt'); // true isRelative('foo.md'); // trueCopy the code

Changes the first character of the string to lowercase

const lowercaseFirst = (str) => `${str.charAt(0).toLowerCase()}${str.slice(1)}`; // example lowercaseFirst('Hello World'); // 'hello World'Copy the code

Repeating a string

const repeat = (str, numberOfTimes) => str.repeat(numberOfTimes); // repeat('ab', 3) // abababCopy the code

Dates

Add the suffix “AM/PM” 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'}`; / / example suffixAmPm (0); // '12am' suffixAmPm(5); // '5am' suffixAmPm(12); // '12pm' suffixAmPm(15); // '3pm' suffixAmPm(23); // '11pm'Copy the code

Count the number of different 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')); / / 1839Copy the code

Check whether the date is valid

const isDateValid = (... val) => ! Number.isNaN(new Date(... val).valueOf()); isDateValid("December 17, 1995 03:24:00"); // trueCopy the code

other

Check that the code is running in Node.js

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

Check that the code is running in the browser

const isBrowser = typeof window === 'object' && typeof document === 'object';
Copy the code

Converts 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 }),{}); / / example 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" }Copy the code

Dark detection mode

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

Copy to clipboard

const copyToClipboard = (text) => navigator.clipboard.writeText(text); // Example copyToClipboard("Hello World");Copy the code

Convert RGB to hexadecimal

const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); // rgbToHex(0, 51, 255); // #0033ffCopy the code

Generates a random hexadecimal color

const randomColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`; / / or const randomColor = () = > ` # ${(~ ~ (math.h random () * (1 < < 24))). ToString (16)} `;Copy the code

Generate random IP addresses

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

Generate random strings using the Node crypto module

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

~~ finish, I am brush bowl wisdom, prepare to hit a drip, we see next period!


Please feel free to discuss in the comments section. The nuggets will draw 100 nuggets in the comments section after the diggnation project. See the event article for details

The bugs that may exist after code deployment cannot be known in real time. In order to solve these bugs, I spent a lot of time on log debugging. Incidentally, I recommend a good BUG monitoring tool for youFundebug.

The original:

Javascript. Plainenglish. IO / 17 – life – sav… Javascript. Plainenglish. IO/another – 17 -…

communication

Have a dream, have dry goods, wechat search [big Move the world] pay attention to this in the early morning is still in the bowl washing wisdom.

In this paper, making github.com/qq449245884… Has been included, a line of large factory interview complete test sites, information and my series of articles.