preface

In daily development, the average programmer often encounters the following scenarios:

  1. Vue: UUID vUE: UUID vUE: UUID vUE: UUID vUE: UUID vUE: UUID vUE: UUID vUE: UUID Google it
  2. Run a complex piece of code, remember like the new H5 ApiWorkerYou can turn on multithreaded execution and avoid blocking, but how do you use it? Google it
  3. When you want to delete a node, add or delete classes to a node, insert a node, etc., you might have done it all before, but just Google it
  4. How do I determine the built-in browser of the ios device on the mobile terminal when I need to perform special operations on an environment due to device compatibility problems? Google it
  5. There is a need to scramble arrays, I did this before, (⊙o⊙)… I don’t think I can write it. Forget it, Google it

Do not know each program ape brothers and sisters have appeared above similar scene, the author is vividly remembered. During development, we implemented many features, either memorized them by rote, or saw how they were implemented. But when it comes to application, the mind goes blank. So as the old saying goes, a bad memory is better than a bad pen. Development is not like an interview, encounter problems follow one’s will, to Baidu on Baidu, to Google on Google, but check the content is uneven, if check the article itself has a problem, that trial and error cost is too high. To avoid the day-to-day googling of the average programmer, this article aims to create a library of native JS snippets for daily development. Can let the general programmer can be out of the box, save extra search time.

Js code snippet using ES6 preparation, has been simplified as far as possible and consider compatibility problems, we can like, collect a wave, in order to use, leisure time can often open to see the implementation principle.

I will update you from time to time. If you have any questions, please discuss them in the comments section. Thank you.

tool

UUID generated

const UUIDGeneratorBrowser = () = >
  ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g.(c) = >
    (
      c ^
      (crypto.getRandomValues(new Uint8Array(1))0] & (15 >> (c / 4)))
    ).toString(16));// Examples
UUIDGeneratorBrowser(); // '7982fcfe-5721-4632-bede-6000885be57d'
Copy the code

Parsing the cookie

const parseCookie = (str) = >
  str
    .split(";")
    .map((v) = > v.split("="))
    .reduce((acc, v) = > {
      acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim());
      return acc;
    }, {});

// Examples
parseCookie("foo=bar; equation=E%3Dmc%5E2");
// { foo: 'bar', equation: 'E=mc^2' }
Copy the code

Get url parameters

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

// Examples
getURLParameters("google.com"); / / {}
getURLParameters("http://url.com/page?name=Adam&surname=Smith");
// {name: 'Adam', surname: 'Smith'}
Copy the code

Copy to the clipboard

The following methods are valid only when the user performs an action, such as the Click event

const copyToClipboard = (str) = > {
  const el = document.createElement("textarea");
  el.value = str;
  el.setAttribute("readonly"."");
  el.style.position = "absolute";
  el.style.left = "-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();
    document.getSelection().addRange(selected); }};// Examples
copyToClipboard("Lorem ipsum"); // 'Lorem ipsum' copied to clipboard.
Copy the code

Simple jquery selector

// Select only the first element
const$=document.querySelector.bind(document);
// Select all
const$$=document.querySelectorAll.bind(document);

const mainContent = $(".main-content");
const externalLinks = $$('a[target="_blank"]');
Copy the code

Multithreaded execution function

const runAsync = (fn) = > {
  const worker = new Worker(
    URL.createObjectURL(new Blob([`postMessage((${fn}) ()); `]) {type: "application/javascript; charset=utf-8",}));return new Promise((res, rej) = > {
    worker.onmessage = ({ data }) = > {
      res(data), worker.terminate();
    };
    worker.onerror = (err) = > {
      rej(err), worker.terminate();
    };
  });
};

// Examples
const longRunningFunction = () = > {
  let result = 0;
  for (let i = 0; i < 1000; i++)
    for (let j = 0; j < 700; j++)
      for (let k = 0; k < 300; k++) result = result + i + j + k;

  return result;
};
/ *NOTE: Since the function is running in a different context, closures are not supported.
  The function supplied to `runAsync` gets stringified, so everything becomes literal.
  All variables and functions must be defined inside.
*/
runAsync(longRunningFunction).then(console.log); / / 209685000000
runAsync(() = > 10支那3).then(console.log); / / 1000
let outsideVariable = 50;
runAsync(() = > typeof outsideVariable).then(console.log); // 'undefined'
Copy the code

Business functions

Determine all data types

@param obj To determine the type of data

@return {string} Data type (lowercase)

const type = (function () {
  // Mapping type
  const classType =
    "Boolean Number String Function Array Date RegExp Object Error Null Undefined"
      .split("")
      .reduce((obj, item) = > {
        obj["[object " + item + "]"] = item.toLowerCase();
        return obj;
      }, {});

  return function (obj) {
    // Only undefined and null are valid
    if (obj == null) {
      return obj + "";
    }
    return typeof obj === "object"
      ? classType[Object.prototype.toString.call(obj)]
      : typeofobj; }; }) ();// Examples
console.log(type(new Date())); // date
console.log(type([1.2])); // array
console.log(type(1)); // number
console.log(type({})); // object
Copy the code

Determining empty objects

function isEmptyObject(obj) {
  if (Object.prototype.toString.call(obj) ! = ="[object Object]") return false;
  var name;
  for (name in obj) {
    return false;
  }
  return true;
}

// Examples
console.log(isEmptyObject({})); // true
console.log(isEmptyObject([])); // false
console.log(isEmptyObject(null)); // false
console.log(isEmptyObject(undefined)); // false
console.log(isEmptyObject(1)); // false
console.log(isEmptyObject("")); // false
console.log(isEmptyObject(true)); // false
Copy the code

Determine the current operating environment

function userAgent() {
  var u = navigator.userAgent;
  return {
    // Mobile terminal browser version information
    trident: u.indexOf("Trident") > -1./ / IE kernel
    presto: u.indexOf("Presto") > -1./ / opera kernel
    webKit: u.indexOf("AppleWebKit") > -1.// Apple, Google kernel
    gecko: u.indexOf("Gecko") > -1 && u.indexOf("KHTML") = = = -1.// The Firefox kernel
    mobile:!!!!! u.match(/AppleWebKit.*Mobile.*/), // Whether it is a mobile terminal
    iPad: u.indexOf("iPad") > -1./ / whether the device
    webApp: u.indexOf("Safari") = = = -1.// Should the web be a program, without a header and a bottom,
    isiOS:!!!!! u.match(/\(i[^;] +; ( U;) ? CPU.+Mac OS X/), / / ios terminal
    isAndroid: u.indexOf("Android") > -1 || u.indexOf("Adr") > -1}; }// Examples
const browser = userAgent();
if (browser.mobile) {
  // Mobile => todo something
  if (browser.isiOS && browser.webApp) {
    // IOS系统 && web程序 => todo something
  } else {
    // Android => todo something}}else {
  // PC => todo something
}
Copy the code

Scroll smoothly to the top of the page

const scrollToTop = () = > {
  const c = document.documentElement.scrollTop || document.body.scrollTop;
  if (c > 0) {
    window.requestAnimationFrame(scrollToTop);
    window.scrollTo(0, c - c / 8); }};// Examples
scrollToTop();
Copy the code

Scrolls the viewport smoothly to the specified element

const smoothScroll = (element) = >
  document.querySelector(element).scrollIntoView({
    behavior: "smooth"});// Examples
smoothScroll("#fooBar");
Copy the code

End of listening scroll

const onScrollStop = (callback) = > {
  let isScrolling;
  window.addEventListener(
    "scroll".(e) = > {
      clearTimeout(isScrolling);
      isScrolling = setTimeout(() = > {
        callback();
      }, 150);
    },
    false
  );
};

// Examples
onScrollStop(() = > {
  console.log("The user has stopped scrolling");
});
Copy the code

Listen for clicks outside the specified element

const onClickOutside = (element, callback) = > {
  document.addEventListener("click".(e) = > {
    if(! element.contains(e.target)) callback(); }); };// Examples
onClickOutside("#my-element".() = > console.log("Hello"));
Copy the code

Gets the current browser language

// defaultLang is the default language
const detectLanguage = (defaultLang = "en-US") = >
  navigator.language ||
  (Array.isArray(navigator.languages) && navigator.languages[0]) ||
  defaultLang;

// Examples
detectLanguage(); // 'nl-NL'
Copy the code

Control and exit the browser in full screen mode

const fullscreen = (mode = true, el = "body") = >
  mode
    ? document.querySelector(el).requestFullscreen()
    : document.exitFullscreen();

// Examples
fullscreen(); // Opens `body` in fullscreen mode
fullscreen(false); // Exits fullscreen mode
Copy the code

Encapsulate native GET and POST requests

const httpGet = (url, callback, err = console.error) = > {
  const request = new XMLHttpRequest();
  request.open("GET", url, true);
  request.onload = () = > callback(request.responseText);
  request.onerror = () = > err(request);
  request.send();
};

const httpPost = (url, data, callback, err = console.error) = > {
  const request = new XMLHttpRequest();
  request.open("POST", url, true);
  request.setRequestHeader("Content-type"."application/json; charset=utf-8");
  request.onload = () = > callback(request.responseText);
  request.onerror = () = > err(request);
  request.send(data);
};

// Examples
httpGet("https://jsonplaceholder.typicode.com/posts/1".console.log); /* Logs: { "userId": 1, "id": 1, "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto" } */

httpPost(
  "https://jsonplaceholder.typicode.com/posts".null.// does not send a body
  console.log
); /* Logs: { "id": 101 } */
Copy the code

DOM manipulation

Element adds, removes, and switches classes

const addClass = (el, className) = > el.classList.add(className);
const removeClass = (el, className) = > el.classList.remove(className);
const toggleClass = (el, className) = > el.classList.toggle(className);

// Examples
addClass(document.querySelector("p"), "special");
removeClass(document.querySelector("p.special"), "special");
toggleClass(document.querySelector("p.special"), "special");
Copy the code

Remove an element

const removeElement = (el) = > el.parentNode.removeChild(el);

// Examples
removeElement(document.querySelector("#my-element"));
Copy the code

Determines whether the specified class is contained on the element

const hasClass = (el, className) = > el.classList.contains(className);

// Examples
hasClass(document.querySelector("p.special"), "special"); // true
Copy the code

Gets the addresses of all images under an element

// includeDuplicates whether to delete duplicates
const getImages = (el, includeDuplicates = false) = > {
  const images = [...el.getElementsByTagName("img")].map((img) = >
    img.getAttribute("src"));return includeDuplicates ? images : [...new Set(images)];
};

// Examples
getImages(document.true); // ['image1.jpg', 'image2.png', 'image1.png', '...']
getImages(document.false); // ['image1.jpg', 'image2.png', '...']
Copy the code

The element that creates the string fragment

// Note: the outermost element must not have siblings. If it does, only the first element will be returned
const createElement = (str) = > {
  const el = document.createElement("div");
  el.innerHTML = str;
  return el.firstElementChild;
};

// Examples
const el = createElement(
  `
      

Hello!

`
); Copy the code

Actively trigger DOM events

const triggerEvent = (el, eventType, detail) = >
  el.dispatchEvent(new CustomEvent(eventType, { detail }));

// Examples
triggerEvent(document.getElementById("myId"), "click");
triggerEvent(document.getElementById("myId"), "click", { username: "bob" });
Copy the code

Date

Gets the total number of days in a month

Using setDatesh(0) sets the date to the last day of the month.

const daysInMonth = (year, month) = > new Date(year, month, 0).getDate();

// Examples
daysInMonth(2020.12)); / / 31
daysInMonth(2024.2)); / / 29
Copy the code

Convert the date to YYYY-MM-DD

const getISODate = (date) = > data.toISOString().split("T") [0];

// Examples
getISODate(new Date()); / / "2021-07-28"
Copy the code

Convert the date to HH:MM:SS

const getColonTimeFromDate = (date) = > date.toTimeString().slice(0.8);

// Examples
getColonTimeFromDate(new Date()); / / '08:38:00'
Copy the code

Returns day, hour, minute, second, millisecond

const formatDuration = (ms) = > {
  if (ms < 0) ms = -ms;
  const time = {
    day: Math.floor(ms / 86400000),
    hour: Math.floor(ms / 3600000) % 24.minute: Math.floor(ms / 60000) % 60.second: Math.floor(ms / 1000) % 60.millisecond: Math.floor(ms) % 1000};return Object.entries(time)
    .filter((val) = > val[1]! = =0)
    .map(([key, val]) = > `${val} ${key}${val ! = =1 ? "s" : ""}`)
    .join(",");
};

// examples
formatDuration(1001); // '1 second, 1 millisecond'
formatDuration(34325055574);
// '397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds'
Copy the code

Returns ISO format for the given number of seconds (’00:00:00′)

const formatSeconds = (s) = > {
  const [hour, minute, second, sign] =
    s > 0
      ? [s / 3600, (s / 60) % 60, s % 60.""]
      : [-s / 3600, (-s / 60) % 60, -s % 60."-"];

  return (
    sign +
    [hour, minute, second]
      .map((v) = > `The ${Math.floor(v)}`.padStart(2."0"))
      .join(":")); };// Examples
formatSeconds(200); / / '00:03:20'
formatSeconds(-200); / / '- 00:03:20'
formatSeconds(99999); / / '27:46:39'
Copy the code

Determine whether the two times are the same

const isSameDate = (dateA, dateB) = >
  dateA.toISOString() === dateB.toISOString();

// Examples
isSameDate(new Date(2010.10.20), new Date(2010.10.20)); // true
Copy the code

Determine if the given year is a leap year

const isLeapYear = (year) = > new Date(year, 1.29).getMonth() === 1;

// Examples
isLeapYear(2019); // false
isLeapYear(2020); // true
Copy the code

Determine whether the given date is a weekend

Using the getDay method, returns 6 on Saturday and 0 on Sunday.

const isWeekend = (d = new Date(a)) = > d.getDay() % 6= = =0;

// Examples
isWeekend(new Date(2021.6.29)); // false
isWeekend(new Date(2021.6.31)); // true
Copy the code

Returns the time after the incremental time was added to the specified date

The setDate method automatically converts dates greater than 31 days.

const addDaysToDate = (date, n) = > {
  const d = new Date(date);
  d.setDate(d.getDate() + n);
  return d.toISOString().split("T") [0];
};

// Examples
addDaysToDate("2020-10-15".10); / / '2020-10-25'
addDaysToDate("2020-10-15", -10); / / '2020-10-05'
Copy the code

algorithm

Quick sort

const quickSort = (arr) = > {
  const a = [...arr];
  if (a.length < 2) return a;
  const pivotIndex = Math.floor(arr.length / 2);
  const pivot = a[pivotIndex];
  const [lo, hi] = a.reduce(
    (acc, val, i) = > {
      if(val < pivot || (val === pivot && i ! = pivotIndex)) { acc[0].push(val);
      } else if (val > pivot) {
        acc[1].push(val);
      }
      returnacc; }, [[], []]);return [...quickSort(lo), pivot, ...quickSort(hi)];
};

// Examples
quickSort([1.6.1.5.3.2.1.4]); // [1, 1, 1, 2, 3, 4, 5, 6]
Copy the code

Selection sort

const selectionSort = (arr) = > {
  const a = [...arr];
  for (let i = 0; i < a.length; i++) {
    const min = a
      .slice(i + 1)
      .reduce((acc, val, j) = > (val < a[acc] ? j + i + 1 : acc), i);
    if(min ! == i) [a[i], a[min]] = [a[min], a[i]]; }return a;
};

// Examples
selectionSort([5.1.4.2.3]); // [1, 2, 3, 4, 5]
Copy the code

Insertion sort

const insertionSort = (arr) = >
  arr.reduce((acc, x) = > {
    if(! acc.length)return [x];
    acc.some((y, j) = > {
      if (x <= y) {
        acc.splice(j, 0, x);
        return true;
      }
      if (x > y && j === acc.length - 1) {
        acc.splice(j + 1.0, x);
        return true;
      }
      return false;
    });
    returnacc; } []);// Examples
insertionSort([6.3.4.1]); // [1, 3, 4, 6]
Copy the code

Bubble sort

const bubbleSort = (arr) = > {
  let swapped = false;
  const a = [...arr];
  for (let i = 1; i < a.length; i++) {
    swapped = false;
    for (let j = 0; j < a.length - i; j++) {
      if (a[j + 1] < a[j]) {
        [a[j], a[j + 1]] = [a[j + 1], a[j]];
        swapped = true; }}if(! swapped)return a;
  }
  return a;
};

// Examples
bubbleSort([2.1.4.3]); // [1, 2, 3, 4]
Copy the code

Merge sort

const mergeSort = (arr) = > {
  if (arr.length < 2) return arr;
  const mid = Math.floor(arr.length / 2);
  const l = mergeSort(arr.slice(0, mid));
  const r = mergeSort(arr.slice(mid, arr.length));
  return Array.from({ length: l.length + r.length }, () = > {
    if(! l.length)return r.shift();
    else if(! r.length)return l.shift();
    else return l[0] > r[0]? r.shift() : l.shift(); }); };// Examples
mergeSort([5.1.4.2.3]); // [1, 2, 3, 4, 5]
Copy the code

Bucket sort

const bucketSort = (arr, size = 5) = > {
  const min = Math.min(... arr);const max = Math.max(... arr);const buckets = Array.from(
    { length: Math.floor((max - min) / size) + 1 },
    () = >[]); arr.forEach((val) = > {
    buckets[Math.floor((val - min) / size)].push(val);
  });
  return buckets.reduce((acc, b) = > [...acc, ...b.sort((a, b) = > a - b)], []);
};

// Examples
bucketSort([6.3.4.1]); // [1, 3, 4, 6]
Copy the code

Binary search

const binarySearch = (arr, item) = > {
  let l = 0,
    r = arr.length - 1;
  while (l <= r) {
    const mid = Math.floor((l + r) / 2);
    const guess = arr[mid];
    if (guess === item) return mid;
    if (guess > item) r = mid - 1;
    else l = mid + 1;
  }
  return -1;
};

// Examples
binarySearch([1.2.3.4.5].1); / / 0
binarySearch([1.2.3.4.5].5); / / 4
binarySearch([1.2.3.4.5].6); // -1
Copy the code

Disrupted array

const shuffle = ([...arr]) = > {
  let m = arr.length;
  while (m) {
    const i = Math.floor(Math.random() * m--);
    [arr[m], arr[i]] = [arr[i], arr[m]];
  }
  return arr;
};

// Examples
shuffle([1.2.3]); / / [2, 3, 1)
Copy the code

Interesting JS

How to implement sleep function in JS

Synchronous version

Date.prototype.gettime () can be used within a while loop to pause execution for a while.

const sleepSync = (ms) = > {
  const end = new Date().getTime() + ms;
  while (new Date().getTime() < end) {
    /* do nothing */}};const printNums = () = > {
  console.log(1);
  sleepSync(500);
  console.log(2);
  console.log(3);
};

printNums(); // Logs: 1, 2, 3 (2 and 3 log after 500ms)
Copy the code

The asynchronous version

const sleep = (ms) = > new Promise((resolve) = > setTimeout(resolve, ms));

const printNums = async() = > {console.log(1);
  await sleep(500);
  console.log(2);
  console.log(3);
};

printNums(); // Logs: 1, 2, 3 (2 and 3 log after 500ms)
Copy the code

After the language

Reference article:

  • 30 Seconds of Code
  • Data type judgment

This article author can update irregularly, everybody can collect.

I will also update some front-end knowledge content and original articles 🎉 from time to time

Your encouragement is the main motivation for my continuous creation 😊.

Related to recommend

  • Front-end Knowledge Base
  • Personal Scaffolding