# 36 * n frequently used JavaScript function fragments in work

Time：2020-11-14

Recently, I saw an article about 36 JavaScript function fragments commonly used in our work.

As an interviewer (█▀█), how can you have only one answer?

## Array

### Array de duplication

#### Scheme 1:`Set + ...`

``````function noRepeat(arr) {
return [...new Set(arr)];
}
noRepeat([1,2,3,1,2,3])``````

#### Scheme 2:`Set + Array.from`

``````function noRepeat(arr) {
return Array.from(new Set(arr));
}
noRepeat([1,2,3,1,2,3])``````

#### Scheme 3: Double traversal comparison subscript

``````function noRepeat(arr) {
return arr.filter((v, idx)=>idx == arr.lastIndexOf(v))
}
noRepeat([1,2,3,1,2,3])``````

#### Scheme 4: single traversal + object feature

The property of object is that the key will not be repeated.
Values are used here because the type can be preserved and keys will become a string.

``````function noRepeat(arr) {
return Object.values(arr.reduce((s,n)=>{
s[n] = n;
return s
},{}))
}
noRepeat([1,2,3,1,2,3])``````

#### Postscript

For the above scheme, there are other variants.

### Find array maximum

#### Scheme 1:`Math.max + ...`

``````function arrayMax(arr) {
return Math.max(...arr);
}
arrayMax([-1,-4,5,2,0])``````

#### Scheme 2:`Math.max + apply`

``````function arrayMax(arr) {
return Math.max.apply(Math, arr)
}
arrayMax([-1,-4,5,2,0])``````

#### Scheme 3:`Math.max`+Traversal

``````function arrayMax(arr) {
return arr.reduce((s,n)=>Math.max(s, n))
}
arrayMax([-1,-4,5,2,0])``````

#### Scheme 4: comparison, conditional operation + traversal

``````function arrayMax(arr) {
return arr.reduce((s,n)=>s>n?s:n)
}
arrayMax([-1,-4,5,2,0])``````

#### Scheme 5: sequencing

``````function arrayMax(arr) {
return arr.sort((n,m)=>m-n)[0]
}
arrayMax([-1,-4,5,2,0])``````

### Find array minimum

ditto,I don’t understand why it’s divided into two topics

1. `Math.max`change into`Math.min`
2. `s>n?s:n`change into`s<n?s:n`
3. `(n,m)=>m-n`change into`(n,m)=>n-m`Or take the last element directly

### Returns the original array split by an array of size

#### Scheme 1: Array.from + slice

``````function chunk(arr, size = 1) {
return Array.from(
{
length: Math.ceil(arr.length / size),
},
(v, i) => arr.slice(i * size, i * size + size)
);
}
chunk([1,2,3,4,5,6,7,8],3)``````

#### Scheme 2: Array.from + splice

``````function chunk(arr, size = 1) {
return Array.from(
{
length: Math.ceil(arr.length / size),
},
(v, i) => arr.splice(0, size)
);
}
chunk([1,2,3,4,5,6,7,8],3)``````

#### Scheme 3: traversal + Split

``````function chunk(arr, size = 1) {
var _returnArr = [];
while(arr.length){
_returnArr.push(arr.splice(0, size))
}
return _returnArr
}
chunk([1,2,3,4,5,6,7,8],3)``````

### Check the number of times an element in the array appears

#### Scheme 1: reduce

``````function countOccurrences(arr, value) {
return arr.reduce((a, v) => (v === value ? a + 1 : a + 0), 0);
}
countOccurrences([1,2,3,4,5,1,2,1,2,3], 1)``````

#### Scheme 2: filter

``````function countOccurrences(arr, value) {
return arr.filter(v=>v===value).length
}
countOccurrences([1,2,3,4,5,1,2,1,2,3], 1)``````

### Flatten array

#### Scheme 1: recursion +

``````function flatten(arr, depth = -1) {
if (depth === -1) {
return [].concat(
...arr.map((v) => (Array.isArray(v) ? this.flatten(v) : v))
);
}
if (depth === 1) {
return arr.reduce((a, v) => a.concat(v), []);
}
return arr.reduce(
(a, v) => a.concat(Array.isArray(v) ? this.flatten(v, depth - 1) : v),
[]
);
}
flatten([1,[2,[3]]])``````

#### Scheme 2: ES6 native flat

``````function flatten(arr, depth = Infinity) {
return arr.flat(depth)
}
flatten([1,[2,[3]]])``````

### Compares two arrays and returns different elements

#### Scheme 1: filter + includes

There are some problems in his original text`4,5`No return

``````function diffrence(arrA, arrB) {
return arrA.filter((v) => !arrB.includes(v));
}
diffrence([1,2,3], [3,4,5,2])``````

You need to do it again

``````function diffrence(arrA, arrB) {
return arrA.filter((v) => !arrB.includes(v))
.concat(arrB.filter((v) => !arrA.includes(v)));
}
diffrence([1,2,3], [3,4,5,2])``````

#### Scheme two: hash + traversal

It’s a variant of scheme 1. It’s optimized`includes`Performance.

### Returns the same element in two arrays

#### Scheme 1: filter + includes

``````function intersection(arr1, arr2) {
return arr2.filter((v) => arr1.includes(v));
}
intersection([1,2,3], [3,4,5,2])``````

#### Scheme 2: hash for homomorphic variants

``````function intersection(arr1, arr2) {
var set = new Set(arr2)
return arr1.filter((v) => set.has(v));
}
intersection([1,2,3], [3,4,5,2])``````

### Remove n elements from the right

#### Scheme 1: slice

``````function dropRight(arr, n = 0) {
return n < arr.length ? arr.slice(0, arr.length - n) : [];
}
dropRight([1,2,3,4,5], 2)``````

#### Scheme 2: split

``````function dropRight(arr, n = 0) {
return arr.splice(0, arr.length - n)
}
dropRight([1,2,3,4,5], 2)``````

#### Scheme 3: slice

``````function dropRight(arr, n = 0) {
return arr.slice(0, -n)
}
dropRight([1,2,3,4,5], 2)``````

#### Scheme 4: modify the length

``````function dropRight(arr, n = 0) {
arr.length = Math.max(arr.length - n, 0)
return arr
}
dropRight([1,2,3,4,5], 2)``````

### Intercepts the first eligible element and subsequent elements

#### Scheme 1: slice + cycle

``````function dropElements(arr, fn) {
while (arr.length && !fn(arr[0])) arr = arr.slice(1);
return arr;
}
dropElements([1,2,3,4,5,1,2,3], (v) => v == 2)``````

#### Scheme 2: FindIndex + slice

``````function dropElements(arr, fn) {
return arr.slice(Math.max(arr.findIndex(fn), 0));
}
dropElements([1,2,3,4,5,1,2,3], (v) => v === 3)``````

#### Scheme 3: split + cycle

``````function dropElements(arr, fn) {
while (arr.length && !fn(arr[0])) arr.splice(0,1);
return arr;
}
dropElements([1,2,3,4,5,1,2,3], (v) => v == 2)``````

### Returns the element of the array with the subscript interval nth

#### Scheme 1: filter

``````function everyNth(arr, nth) {
return arr.filter((v, i) => i % nth === nth - 1);
}
everyNth([1,2,3,4,5,6,7,8], 2)``````

#### Scheme 2: modification of judgment conditions for scheme 1

``````function everyNth(arr, nth) {
return arr.filter((v, i) => (i+1) % nth === 0);
}
everyNth([1,2,3,4,5,6,7,8], 2)``````

### Returns the nth element in an array (negative numbers are supported)

#### Scheme 1: slice

``````function nthElement(arr, n = 0) {
return (n >= 0 ? arr.slice(n, n + 1) : arr.slice(n))[0];
}
nthElement([1,2,3,4,5], 0)
nthElement([1,2,3,4,5], -1)``````

#### Scheme 2: ternary operator

``````function nthElement(arr, n = 0) {
return (n >= 0 ? arr[0] : arr[arr.length + n])
}
nthElement([1,2,3,4,5], 0)
nthElement([1,2,3,4,5], -1)``````

### Returns the array header element

#### Scheme 1:

``````function head(arr) {
return arr[0];
}

#### Scheme 2:

``````function head(arr) {
return arr.slice(0,1)[0];
}

### Returns the element at the end of an array

#### Scheme 1:

``````function last(arr) {
return arr[arr.length - 1];
}``````

#### Scheme 2:

``````function last(arr) {
return arr.slice(-1)[0];
}
last([1,2,3,4,5])``````

### Array shuffling

#### Scheme one: shuffling algorithm

``````function shuffle(arr) {
let array = arr;
let index = array.length;

while (index) {
index -= 1;
let randomInedx = Math.floor(Math.random() * index);
let middleware = array[index];
array[index] = array[randomInedx];
array[randomInedx] = middleware;
}

return array;
}
shuffle([1,2,3,4,5])``````

#### Scheme 2: sort + random

``````function shuffle(arr) {
return arr.sort((n,m)=>Math.random() - .5)
}
shuffle([1,2,3,4,5])``````

### Convert pseudo array to array

#### Scheme 1: Array.from

``Array.from({length: 2})``

#### Scheme 2: prototype.slice

``Array.prototype.slice.call({length: 2,1:1})``

#### Scheme 3: prototype.splice

``Array.prototype.splice.call({length: 2,1:1},0)``

## Browser object BOM

### Determine whether the browser supports CSS properties

``````/**
*Informs the browser of the specified CSS properties supported
*The @ param {string} key - CSS property is the name of the attribute and does not need to be prefixed
*@ returns {string} - supported properties
*/
function validateCssKey(key) {
Const jskey = tocamelcase (key); // some CSS attributes are formed by hyphens
if (jsKey in document.documentElement.style) {
return key;
}
let validKey = "";
//The property name is the form of prefix in JS, and the property value is the form of prefix in CSS
//After trying, WebKit is also a lowercase WebKit
const prefixMap = {
Webkit: "-webkit-",
Moz: "-moz-",
ms: "-ms-",
O: "-o-",
};
for (const jsPrefix in prefixMap) {
const styleKey = toCamelCase(`\${jsPrefix}-\${jsKey}`);
if (styleKey in document.documentElement.style) {
validKey = prefixMap[jsPrefix] + key;
break;
}
}
return validKey;
}

/**
*Convert the string with hyphenation into the string of hump nomenclature
*/
function toCamelCase(value) {
return value.replace(/-(\w)/g, (matched, letter) => {
return letter.toUpperCase();
});
}

/**
*Check whether the browser supports a CSS property value (ES6 version)
*@ param {string} key - the CSS property name of the property value to be checked
*@ param {string} value - CSS property value to check (without prefix)
*@ returns {string} - returns the property values supported by the browser
*/
function valiateCssValue(key, value) {
const prefix = ["-o-", "-ms-", "-moz-", "-webkit-", ""];
const prefixValue = prefix.map((item) => {
return item + value;
});
const element = document.createElement("div");
const eleStyle = element.style;
//The application of each prefix, and finally the application of no prefix, depends on what happens to the browser
//This is the last element that's best in prefix, which is' '
prefixValue.forEach((item) => {
eleStyle[key] = item;
});
return eleStyle[key];
}

/**
*Check whether the browser supports a CSS property value
*@ param {string} key - the CSS property name of the property value to be checked
*@ param {string} value - CSS property value to check (without prefix)
*@ returns {string} - returns the property values supported by the browser
*/
function valiateCssValue(key, value) {
var prefix = ["-o-", "-ms-", "-moz-", "-webkit-", ""];
var prefixValue = [];
for (var i = 0; i < prefix.length; i++) {
prefixValue.push(prefix[i] + value);
}
var element = document.createElement("div");
var eleStyle = element.style;
for (var j = 0; j < prefixValue.length; j++) {
eleStyle[key] = prefixValue[j];
}
return eleStyle[key];
}

function validCss(key, value) {
const validCss = validateCssKey(key);
if (validCss) {
return validCss;
}
return valiateCssValue(key, value);
}``````

https://segmentfault.com/a/11…
It has foreach in it.

#### Scheme 1: Location

``````function currentURL() {
return window.location.href;
}
currentURL()``````

#### Scheme 2: a label

``````function currentURL() {
var el = document.createElement('a')
el.href = ''
return el.href
}
currentURL()``````

### Get scroll bar position

``````function getScrollPosition(el = window) {
return {
x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop,
};
}``````

### Get the parameters in the URL

#### Scheme 1: regular + reduce

``````function getURLParameters(url) {
return url
.match(/([^?=&]+)(=([^&]*))/g)
.reduce(
(a, v) => (
(a[v.slice(0, v.indexOf("="))] = v.slice(v.indexOf("=") + 1)), a
),
{}
);
}
getURLParameters(location.href)``````

#### Scheme 2: split + reduce

``````function getURLParameters(url) {
return url
. split ('?') // access? division
. slice (1) // no first part
. join() // splicing
. split ('&') / & split
. map (v = > v. split ('=')) // = split
.reduce((s,n)=>{s[n[0]] = n[1];return s},{})
}
getURLParameters(location.href)
// getURLParameters('')``````

### Page Jump, is it recorded in history

#### Scheme 1:

``````function redirect(url, asLink = true) {
asLink ? (window.location.href = url) : window.location.replace(url);
}``````

#### Scheme 2:

``````function redirect(url, asLink = true) {
}``````

#### Scheme 1: C – C / 8

C has no definition

``````function scrollToTop() {
const scrollTop =
document.documentElement.scrollTop || document.body.scrollTop;
if (scrollTop > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
} else {
window.cancelAnimationFrame(scrollToTop);
}
}
scrollToTop()``````

After amendment

``````function scrollToTop() {
const scrollTop =
document.documentElement.scrollTop || document.body.scrollTop;
if (scrollTop > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, scrollTop - scrollTop / 8);
} else {
window.cancelAnimationFrame(scrollToTop);
}
}
scrollToTop()``````

### Copy text

#### Scheme 1:

``````function copy(str) {
const el = document.createElement("textarea");
el.value = str;
el.style.position = "absolute";
el.style.left = "-9999px";
el.style.top = "-9999px";
document.body.appendChild(el);
const selected =
document.getSelection().rangeCount > 0
? document.getSelection().getRangeAt(0)
: false;
el.select();
document.execCommand("copy");
document.body.removeChild(el);
if (selected) {
document.getSelection().removeAllRanges();
}
}``````

### Type of testing equipment

#### Scheme 1: UA

``````function detectDeviceType() {
navigator.userAgent
)
? "Mobile"
: "Desktop";
}
detectDeviceType()``````

#### Scheme 2: Event Attributes

``````function detectDeviceType() {
return ("ontouchstart" in window || navigator.msMaxTouchPoints)
? "Mobile"
: "Desktop";
}
detectDeviceType()``````

### increase

``````function setCookie(key, value, expiredays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + expiredays);
key +
"=" +
escape(value) +
(expiredays == null ? "" : ";expires=" + exdate.toGMTString());
}``````

### Delete

``````function delCookie(name) {
var exp = new Date();
exp.setTime(exp.getTime() - 1);
if (cval != null) {
document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}
}``````

### check

``````function getCookie(name) {
var arr,
reg = new RegExp("(^| )" + name + "=([^;]*)(;|\$)");
return arr[2];
} else {
return null;
}
}``````

### empty

Sometimes we want to empty, but we can’t get all the cookies.
At this time, we can use the method of filling and then clearing.

## Date

### Timestamp to time

• The default is the current time conversion result
• Isms is whether the timestamp is Ms
``````function timestampToTime(timestamp = Date.parse(new Date()), isMs = true) {
const date = new Date(timestamp * (isMs ? 1 : 1000));
return `\${date.getFullYear()}-\${
date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1
}-\${date.getDate()} \${date.getHours()}:\${date.getMinutes()}:\${date.getSeconds()}`;
}``````
2. The complement can also be changed to slice

If I do overseas, there will be some problems. Generally, I use moment to solve them. If you want to see the original

### Gets the current timestamp

Based on the previous question

### Document object DOM

#### Fixed scroll bar

``````/**
*Function Description: some business scenarios, such as the pop-up box, need to prohibit page scrolling. This is a solution compatible with Android and IOS
*/

let scrollTop = 0;

function preventScroll() {
//Store current scroll position
scrollTop = window.scrollY;

//The scrollable area is fixed and cannot be rolled when the height of the scrollable area is 0
document.body.style["overflow-y"] = "hidden";
document.body.style.position = "fixed";
document.body.style.width = "100%";
document.body.style.top = -scrollTop + "px";
// document.body.style['overscroll-behavior'] = 'none'
}

function recoverScroll() {
document.body.style["overflow-y"] = "auto";
document.body.style.position = "static";
// document.querySelector('body').style['overscroll-behavior'] = 'none'

window.scrollTo(0, scrollTop);
}``````

### Determine whether the current position is at the bottom of the page

• The return value is true / false
``````function bottomVisible() {
return (
document.documentElement.clientHeight + window.scrollY >=
(document.documentElement.scrollHeight ||
document.documentElement.clientHeight)
);
}``````

### Determine whether the element is visible

• Partiallyvisible is whether it is fully visible or not
``````function elementIsVisibleInViewport(el, partiallyVisible = false) {
const { top, left, bottom, right } = el.getBoundingClientRect();

return partiallyVisible
? ((top > 0 && top < innerHeight) ||
(bottom > 0 && bottom < innerHeight)) &&
((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
: top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
}``````

### Get element CSS Style

``````function getStyle(el, ruleName) {
return getComputedStyle(el, null).getPropertyValue(ruleName);
}``````

### Enter full screen

``````function launchFullscreen(element) {
if (element.requestFullscreen) {
element.requestFullscreen();
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if (element.msRequestFullscreen) {
element.msRequestFullscreen();
} else if (element.webkitRequestFullscreen) {
element.webkitRequestFullScreen();
}
}

launchFullscreen(document.documentElement);
launchFullscreen( document.getElementById ("Id"); // an element enters the full screen``````

### Exit full screen

``````function exitFullscreen() {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
}

exitFullscreen();``````

### Full screen events

``````document.addEventListener("fullscreenchange", function (e) {
if (document.fullscreenElement) {
console.log ("enter full screen");
} else {
console.log ("exit full screen");
}
});``````

## Number

### Digital thousand percentile segmentation

``````function commafy(num) {
return num.toString().indexOf(".") !== -1
? num.toLocaleString()
: num.toString().replace(/(\d)(?=(?:\d{3})+\$)/g, "\$1,");
}
commafy(1000)``````

### Generating random numbers

``````function randomNum(min, max) {
switch (arguments.length) {
case 1:
return parseInt(Math.random() * min + 1, 10);
case 2:
return parseInt(Math.random() * (max - min + 1) + min, 10);
default:
return 0;
}
}
randomNum(1,10)``````

## WeChat official account: front-end Linong

Welcome to my official account. If you have any questions, you can add my wechat front-end communication group.

## Java book list

Java Basics 《Head First Java》 Some people say this book is not suitable for novice programmers? In fact, this book is very suitable for novices who have a little experience to read, of course, it is also suitable for us to review java knowledge. PS: just started programming, the best way is to learn by […]