Time format conversion

Method of use: parseTime (1622536859864, "{y} {m} - {d} {h} : {I}") output: "the 2021-06-01 16:40:59"Copy the code
/** * Parse the time to string * @param {(Object|string|number)} time * @param {string} cFormat * @returns {string | null} */ export function parseTime(time, cFormat) { if (arguments.length === 0 || ! time) { return null; } const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}"; let date; if (typeof time === "object") { date = time; } else { if (typeof time === "string") { if (/^[0-9]+$/.test(time)) { // support "1548221490638" time = parseInt(time); } else if (/T/g.test(time)) { time = new Date(time); } else { time = time.replace(new RegExp(/-/gm), "/"); } } if (typeof time === "number" && time.toString().length === 10) { time = time * 1000; } date = new Date(time); } const formatObj = { y: date.getFullYear(), m: date.getMonth() + 1, d: date.getDate(), h: date.getHours(), i: date.getMinutes(), s: date.getSeconds(), a: date.getDay() }; const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => { const value = formatObj[key]; / / Note: getDay () returns 0 on Sunday if (key = = = "a") {return [" day ", "a", "2", "three", "four", "five", "six"] [value]; } return value.toString().padStart(2, "0"); }); return time_str; }Copy the code

Past distance current time format conversion

Usage: formatTime(1622536859864); Output: 6 minutes agoCopy the code
/** * @param {number} time * @param {string} option * @returns {string} */ export function formatTime(time, option) { if (("" + time).length === 10) { time = parseInt(time) * 1000; } else { time = +time; } const d = new Date(time); const now = Date.now(); const diff = (now - d) / 1000; If (diff < 30) {return "just "; } else if (diff < 3600) {// less 1 hour return math.ceil (diff / 60) + "minutes ago "; } else if (diff < 3600 * 24) {return math.ceil (diff / 3600) + "hours ago "; } else if (diff < 3600 * 24 * 2) {return "1 day ago "; } if (option) { return parseTime(time, option); } else {return (d.getMonth() + 1 + "month" + D.getDate () + "day" + D.geours () + ":" + D.getminutes ().toString()) .padStart(2, "0") ); }}Copy the code

Gets the specified or URL parameter

GetQueryObject ("https://www.baidu.com?channel=weixin"); Output: {channel: "weixin"}Copy the code
/** * @param {string} url * @returns {Object} */ export function getQueryObject(url) { url = url == null ? window.location.href : url; const search = url.substring(url.lastIndexOf("?" ) + 1); const obj = {}; const reg = /([^?&=]+)=([^?&=]*)/g; search.replace(reg, (rs, $1, $2) => { const name = decodeURIComponent($1); let val = decodeURIComponent($2); val = String(val); obj[name] = val; return rs; }); return obj; }Copy the code

Gets the string length in bytes

ByteLength (" Hello, silencer "); Output: 18Copy the code
/**
 * @param {string} input value
 * @returns {number} output value
 */
export function byteLength(str) {
  let s = str.length;
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i);
    if (code > 0x7f && code <= 0x7ff) s++;
    else if (code > 0x7ff && code <= 0xffff) s += 2;
    if (code >= 0xdc00 && code <= 0xdfff) i--;
  }
  return s;
}
Copy the code

Merges two pure objects

/**
 *
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
export function objectMerge(target, source) {
  if (typeof target !== "object") {
    target = {};
  }
  if (Array.isArray(source)) {
    return source.slice();
  }
  Object.keys(source).forEach(property => {
    const sourceProperty = source[property];
    if (typeof sourceProperty === "object") {
      target[property] = objectMerge(target[property], sourceProperty);
    } else {
      target[property] = sourceProperty;
    }
  });
  return target;
}
Copy the code

Switch the style

/** * @param {HTMLElement} element * @param {string} className */ export function toggleClass(element, className) { if (! element || ! className) { return; } let classString = element.className; const nameIndex = classString.indexOf(className); if (nameIndex === -1) { classString += "" + className; } else { classString = classString.substr(0, nameIndex) + classString.substr(nameIndex + className.length); } element.className = classString; }Copy the code

Function image stabilization

export function debounce(func, wait, immediate) { let timeout, args, context, timestamp, result; Const later = function() {const last = +new Date() -timestamp; Wait if (last < wait && last > 0) {timeout = setTimeout(later, wait-last); wait if (last < wait && last > 0) {timeout = setTimeout(later, wait-last); } else { timeout = null; // If immediate===true, you do not need to call if (! immediate) { result = func.apply(context, args); if (! timeout) context = args = null; }}}; return function(... args) { context = this; timestamp = +new Date(); const callNow = immediate && ! timeout; // If delay does not exist, reset delay if (! timeout) timeout = setTimeout(later, wait); if (callNow) { result = func.apply(context, args); context = args = null; } return result; }; }Copy the code

Function of the throttle

/** * Function throttle * @param {Function} func * @param {Number} wait * @returns */ export Function throttle(func, wait) { var timeout; return function() { var _this = this, args = arguments; if (! timeout) { timeout = setTimeout(() => { timeout = null; func.apply(_this, args); }, wait); }}; }Copy the code

A deep clone

/** * @param {Object} source * @returns {Object} */ export function deepClone(source) { if (! source && typeof source ! == "object") { throw new Error("error arguments", "deepClone"); } const targetObj = source.constructor === Array ? [] : {}; Object.keys(source).forEach(keys => { if (source[keys] && typeof source[keys] === "object") { targetObj[keys] = deepClone(source[keys]); } else { targetObj[keys] = source[keys]; }}); return targetObj; }Copy the code

Array to heavy

/**
 * @param {Array} arr
 * @returns {Array}
 */
export function uniqueArr(arr) {
  return Array.from(new Set(arr));
}
Copy the code

Unique string

/**
 * @returns {string}
 */
export function createUniqueString() {
  const timestamp = +new Date() + "";
  const randomNum = parseInt((1 + Math.random()) * 65536) + "";
  return (+(randomNum + timestamp)).toString(32);
}
Copy the code

Whether the node contains a style class name

export function hasClass(ele, cls) { return !! ele.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)")); }Copy the code

The node adds the style class name

export function addClass(ele, cls) { if (! hasClass(ele, cls)) ele.className += " " + cls; }Copy the code

Removes the style class name

export function removeClass(ele, cls) { if (hasClass(ele, cls)) { const reg = new RegExp("(\\s|^)" + cls + "(\\s|$)"); ele.className = ele.className.replace(reg, " "); }}Copy the code

Determining the Terminal Type

export function getClient(){ const ua = navigator.userAgent; let env = { ua: ua, isMobile: /android|iphone|ipod|ipad/i.test(ua), isIOS: /iphone|ipod|ipad|ios|mac os/i.test(ua), isAndroid: /android/i.test(ua), isWechat: /micromessenger/i.test(ua), isQQ: /qq\//i.test(ua), isWeibo: /weibo/i.test(ua), isDingTalk: /dingtalk/i.test(ua) }; env.isBrowser = ! ( env.isWechat || env.isQQ || env.isWeibo || env.isDingTalk ); return env; }Copy the code

Check if it is a pure object

  var _toString = Object.prototype.toString;
  function isPlainObject(obj) {
    return _toString.call(obj) === "[object Object]";
  }
Copy the code

Numeric type conversion

  function toNumber(val) {
    var n = parseFloat(val);
    return isNaN(n) ? val : n;
  }

Copy the code

Determines whether two data types are not strictly equal

function looseEqual(a, b) { if (a === b) { return true; } var isObjectA = isObject(a); var isObjectB = isObject(b); if (isObjectA && isObjectB) { try { var isArrayA = Array.isArray(a); var isArrayB = Array.isArray(b); if (isArrayA && isArrayB) { return ( a.length === b.length && a.every(function (e, i) { return looseEqual(e, b[i]); })); } else if (a instanceof Date && b instanceof Date) { return a.getTime() === b.getTime(); } else if (! isArrayA && ! isArrayB) { var keysA = Object.keys(a); var keysB = Object.keys(b); return ( keysA.length === keysB.length && keysA.every(function (key) { return looseEqual(a[key], b[key]); })); } else { /* istanbul ignore next */ return false; } } catch (e) { /* istanbul ignore next */ return false; } } else if (! isObjectA && ! isObjectB) { return String(a) === String(b); } else { return false; }}Copy the code

Only call the function once

  function once(fn) {
    var called = false;
    return function () {
      if (!called) {
        called = true;
        fn.apply(this, arguments);
      }
    };
  }
Copy the code

Number formatting

@param {Number} num * @param {Number} digits */ export function NumberFormatter (num, digits = 2, round) {const si = [{value: 1e9, symbol: "m"}, {value: 1e4, symbol: "m"}]; for (let i = 0; i < si.length; i++) { if (num >= si[i].value) { if (round) { return ( String( Math.floor((num / si[i].value) * Math.pow(10,digits)) / Math.pow(10,digits) ).replace(/\.0+$|(\.[0-9]*[1-9])0+$/, "$1") + si[i].symbol ); } else { return ( (num / si[i].value) .toFixed(digits) .replace(/\.0+$|(\.[0-9]*[1-9])0+$/, "$1") + si[i].symbol ); } } } return num.toFixed(digits); }Copy the code

Digit thousands format

/** * 10000 => "10000" * @param {number} num */ export function toThousandFilter(num, digits = 2) { return (+num || 0) .toFixed(digits) .replace(/^-? \d+/g, m => m.replace(/(? = (? ! \b)(\d{3})+$)/g, ",")); }Copy the code

The first letter of the string is uppercase

export function uppercaseFirst(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}
Copy the code