banner
{小朋友}

xiaopy

Common Methods

  • Commonly Used Utility Functions

new Map#

new Map MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

const map = new Map();
map.set("first",1);  // Output structure Map(2) {'first' => 1}
map.has("first") // true Go back to the has table to check if there is a matching key, if so true, otherwise false
map.get("first") // 1 Get the value corresponding to the key, return undefined if not found

/**
 * for of method to iterate Map
 */
const map = new Map();
map.set(1,"one");
map.set(2,"two");
for (let [key,value] of map){ // Can get both key and value at the same time
  console.log(key,value) // 1,one   2,two
}
for (let key of map.keys()){  // Can only get the keys
  console.log(key) // 1  2
}

/**
 * Algorithm problem of two numbers summing
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
const twoSum = function(nums, target) {
    const map = new Map();
    for(let i = 0;i<nums.length;i++){
        if(map.has(target - nums[i])){
            return [map.get(target - nums[i]),i]
        }else{
            map.set(nums[i],i)
        }
    }
};

const nums = [2,4,5,7,10]

const target = 14

twoSum(nums,target) // [1,4]  Output the indices of the values that equal the target

String Number Reversal#

/**
 * @param {number} num
 * @return {boolean}
 */
const isPalindrome = function(num) {
  if (num === 0){
     return true;
  }
  const str = num + '';
  let result = '';
  for (let i = 0;i<str.length;i++){
    result += str[str.length-1-i];
  }
  if (str === result){
     return true;
  }else{
     return false;
  }
}

String Conversion - (Camel Case to Underscore / Underscore to Camel Case)#

/**
 * Underscore to Camel Case
 * @return
 */
const toHump = (result) => {
    return result.replace(/\_(\w)/g, function(_, res){
        return res.toUpperCase();
    });
}

/**
 * Camel Case to Underscore
 * @return
 */
const toUnderline = (result) => {
  return result.replace(/([A-Z])/g,"_$1").toLowerCase();
}

localStorage Operations#

class Catch {
    constructor(isLocal = true) {
      this.storage = isLocal ? localStorage : sessionStorage;
    }

    setItem(key, value) {
      if (typeof value === "object") value = JSON.stringify(value);
      this.storage.setItem(key, value);
    }

    getItem(key) {
      try {
          return JSON.parse(this.storage.getItem(key));
      } catch (err) {
          this.storage.getItem(key);
      }
    }

    removeItem(key) {
      this.storage.removeItem(key);
    }

    clear() {
      this.storage.clear();
    }

    key(index) {
      return this.storage.key(index);
    }

    length() {
      return this.storage.length;
    }
}

const localCache = new Catch();
const sessionCache = new Catch(false);

export { localCache, sessionCache };
/**
 * Get cookie
 * @return string
 */
const getCookie = (name) => {
    const strcookie = document.cookie; // Get cookie string
    const arrcookie = strcookie.split("; "); // Split
    for ( let i = 0; i < arrcookie.length; i++) {
        const arr = arrcookie[i].split("=");
        if (arr[0] == name){
            return arr[1];
        }
    }
    return "";
}

/**
 * Get all cookies
 * @return string
 */
const print = () => {
    const strcookie = document.cookie; // Get cookie string
    const arrcookie = strcookie.split(";"); // Split
    for ( let i = 0; i < arrcookie.length; i++) {
        const arr = arrcookie[i].split("=");
        console.log(arr[0] +"=" + arr[1]);
    }
}
const print = () => {
    return eval('({' + document.cookie.replaceAll('=', ":'").replaceAll(';', "',") + "'})");
}

/**
 * Cookie add, delete, modify
 */
const cookieManager = {
  set(key, val) {
    // Set cookie method
    const date = new Date(); // Get current time
    const expiresDays = 1; // 1 day
    date.setTime(date.getTime() + expiresDays * 24 * 3600 * 1000); // Format to cookie recognizable time
    document.cookie = key + '=' + val + ';expires=' + date.toGMTString(); // Set cookie
    console.log(key + '=' + val + ';expires=' + date.toGMTString(),'val....')
  },
  get(key) {
    // Get cookie method
    /* Get cookie parameters */
    const cookies = document.cookie.replace(/[ ]/g, ''); // Get cookie and format it, removing space characters
    const arrCookie = cookies.split(';'); // Save the obtained cookie in arrCookie array using "semicolon" as the identifier
    let tips; // Declare variable tips
    for (let i = 0; i < arrCookie.length; i++) {
      // Use for loop to find tips variable in cookie
      const arr = arrCookie[i].split('='); // Save single cookie as arr array using "equal sign" as the identifier
      if (key == arr[0]) {
        // Match variable name, where arr[0] refers to cookie name, if this variable is tips then execute the assignment operation in the judgment statement
        tips = arr[1]; // Assign the cookie value to tips variable
        break; // Terminate for loop traversal
      }
    }
    return tips;
  },
  del(key) {
    // Delete cookie method
    const date = new Date(); // Get current time
    date.setTime(date.getTime() - 10000); // Set date to past time
    document.cookie = key + '=v; expires =' + date.toGMTString(); // Set cookie
  },
};

Throttle and Debounce (Test Cases)#

/**
 * Debounce
 */
const debounce = (fn, delay) => {
  let timer;
  return function () {
    const arg = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.apply(this, arg);
    }, delay);
  };
};


/**
 * Throttle
 */
const throttle = (fn, delay) => {
  let timer;
  return function () {
    let _this = this;
    let args = arguments;
    if (timer) {
      return;
    }
    timer = setTimeout(function () {
      fn.apply(_this, args);
      timer = null;
    }, delay);
  };
};

/**
 * Timestamp Throttle
 */
function timestamThrottle(fn, delay) {
  let previous = 0;
  // Use closure to return a function and use the outer variable previous
  return function () {
    let now = new Date();
    if (now - previous > delay) {
      fn.apply(this, arguments);
      previous = now;
    }
  };
}


/**
 * Test Case 
 * Using debounce function as an example
 */
const debounceFn = debounce((e) => {
  console.log(e);
}, 500); // Debounce function
document.onmousemove = (e) => {
  debounceFn(e); // Pass parameters to debounce function
};

Listen for Copy/Cut Events#

/**
 * Listen for copy
 */
(function () {
  document.addEventListener('copy', (e) => {
    const selection = document.getSelection();
    e.clipboardData.setData('text/plain', selection.toString().toUpperCase());
    e.preventDefault();
    e.stopPropagation();
    let copy = (e.clipboardData || window.clipboardData).getData('text/plain');
    copy = copy.replace(/style/gi, 'data-style');
    console.log(copy, 'copy');
  });
})();

/**
 * Listen for cut
 */
(function () {
  document.addEventListener('cut', (e) => {
    const selection = document.getSelection();
    e.clipboardData.setData('text/plain', selection.toString().toUpperCase());
    document.getSelection().deleteFromDocument();
    e.preventDefault();
    e.stopPropagation();
    let cut = (e.clipboardData || window.clipboardData).getData('text/plain');
    cut = cut.replace(/style/gi, 'data-style');
    console.log(cut, 'cut');
  });
})();

Recursion#

/**
 * Return all parent structure data of the current data (including itself)
 * @param list = []
 * @param id: number
 */
function getParentId(list, id) {
    for (let i in list) {
        if (list[i].value == id) {
            return [list[i]];
        }
        if (list[i].children) {
            let node = getParentId(list[i].children, id);
            if (node !== undefined) {
                return node.concat(list[i]);
            }
        }
    }
}

/**
 * Recursively find specified data
 * @param list = []
 * @param id: number
 */
function getCurrent(list, id) {
    for (let o of list || []) {
        if (o.value == id) return o
        const o_ = getCurrent(o.children, id)
        if (o_) return o_
    }
}

// When parentId and id are the same, it becomes the subset data of id
// Initial data
var data = [
  { id: 2, parentId: 1 },
  { id: 1 },
  { id: 3, parentId: 2 },
  { id: 5, parentId: 4 },
  { id: 4 },
];
// Processed data
/*[
    {
      id: 1,
      child: [{
          id: 2, 
          parentId: 1, 
          child: [{
              id: 3,
              parentId: 2
          }]
      }]
   },
    {id: 4, child: [{id: 5, parentId: 4}]},
  ]*/
function returnData(arr) {
  // Initially no superior data and
  let parents = arr.filter((item) => !item.parentId);
  // Initially there is superior data and
  let childs = arr.filter((item) => item.parentId);
  // Recursively process data
  function newData(parents, childs) {
    parents.forEach((item) => {
      childs.forEach((child, childIndex) => {
        if (item.id === child.parentId) {
          let newChilds = JSON.parse(JSON.stringify(childs));
          newChilds.splice(childIndex, 1); // Delete already existing data
          item.childs = item.childs ? item.childs.push(child) : [child];
          newData([child], newChilds);
        } else {
          return false;
        }
      });
    });
  }
  newData(parents, childs);
  return parents;
}
let a = [];
console.log((a = returnData(data)));

// Filtering
// Example
const memberList = [
  {
    name: "Development Department",
    member: [
      {
        name: "Frontend",
        member: [
          {
            name: "Zhang San",
            age: 18,
            member: [],
          },
        ],
      },
      {
        name: "Backend",
        member: [
          {
            name: "Li Si",
            age: 24,
            member: [],
          },
        ],
      },
    ],
  },
  {
    name: "Marketing Department",
    member: [
      {
        name: "Supervisor",
        member: [
          {
            name: "Wang Wu",
            age: 30,
            member: [],
          },
        ],
      },
      {
        name: "Manager",
        member: [
          {
            name: "Lao Liu",
            age: 28,
            member: [],
          },
        ],
      },
    ],
  },
];

// Filter name values and return as an array
const getAllMember = (arr) => {
    let member = [];
    arr.forEach(item => {
        if (item.member && item.member.length) {
            member = [
                ...member,
                ...getAllMember(item.member)
            ]
        } else {
            member.push(item.name);
        }
    });
    return member;
}

// Filter data with age less than 20
const filterMember = (key, data) => {
  const filterList = [];

  data.forEach((ele) => {
    const { member, ...other } = ele;

    if (member && member.length) {
      const currentEle = {
        member: [],
        ...other,
      };
      const result = filterMember(key, member);

      if (result.length) {
        currentEle.member = result;
        filterList.push(currentEle);
      }
    } else if (other.age > key) {
      filterList.push(other);
    }
  });
  return filterList;
};

Listen for User's DevTools Opening Behavior#

(function () {
    var devtools = {
      open: false,
      orientation: null,
    };
    var threshold = 160;
    var emitEvent = function (state, orientation) {
      window.dispatchEvent(
        new CustomEvent("devtoolschange", {
          detail: {
            open: state,
            orientation: orientation,
          },
        })
      );
    };
    clearTimer = setInterval(function () {
      var widthThreshold = window.outerWidth - window.innerWidth > threshold;
      var heightThreshold = window.outerHeight - window.innerHeight > threshold;
      var orientation = widthThreshold ? "vertical" : "horizontal";

      if (
        !(heightThreshold && widthThreshold) &&
        ((window.Firebug &&
          window.Firebug.chrome &&
          window.Firebug.chrome.isInitialized) ||
          widthThreshold ||
          heightThreshold)
      ) {
        if (!devtools.open || devtools.orientation !== orientation) {
          emitEvent(true, orientation);
        }
        devtools.open = true;
        devtools.orientation = orientation;
      } else {
        if (devtools.open) {
          emitEvent(false, null);
        }
        devtools.open = false;
        devtools.orientation = null;
      }
    }, 500);
    if (typeof module !== "undefined" && module.exports) {
      module.exports = devtools;
    } else {
      window.devtools = devtools;
    }
  })();
  
  window.addEventListener("devtoolschange", function (e) {
     console.log(e.detail)
  });

Listen for Real-Time Changes of a Specific Element#

/**
 * Listen for real-time changes of a specific element
 */
export const ListeningTagAttribute = () => {
    setTimeout(() => {
      // Select the element to listen to
      const targetNode = document.getElementById('detail-content');
  
      // Create an observer instance and pass in the callback function
      const observer = new MutationObserver((mutationsList, observer) => {
        // Loop through each change
        for (let mutation of mutationsList) {
          console.log(mutation, mutationsList)
          if (mutation.type === 'attributes') {
            console.log('Attribute value has changed:', mutation.attributeName, mutation.target.getAttribute(mutation.attributeName));
          }
        }
      });
  
      // Configure observer options
      const config = { attributes: true, childList: false, subtree: false };
      // Pass the target node and observer configuration object
      observer.observe(targetNode, config);
    }, 3000)
  }

URL Parsing / Handling URL Parameter Field Replacement#

/**
 * @param {string} url Address 
 * @param {string} arg Parameter name to be replaced
 * @param {any} arg_val Parameter to be replaced
 * @returns Returns the processed url
 */
function changeURLArg(url,arg,arg_val){ 
    let pattern=arg+'=([^&]*)'; 
    let replaceText=arg+'='+arg_val; 
    if(url.match(pattern)){ 
        let tmp='/('+ arg+'=)([^&]*)/gi'; 
        tmp=url.replace(eval(tmp),replaceText); 
        return tmp; 
    }else{ 
        if(url.match('[\?]')){ 
            return url+'&'+replaceText; 
        }else{ 
            return url+'?'+replaceText; 
        } 
    } 
    return url+'\n'+arg+'\n'+arg_val; 
}

// Parse into object
function queryURLparams(url) {
    let obj = {}
    if (url.indexOf('?') < 0) return obj
    let arr = url.split('?')
    url = arr[1]
    let array = url.split('&')
    for (let i = 0; i < array.length; i++) {
        let arr2 = array[i]
        let arr3 = arr2.split('=')
        obj[arr3[0]] = arr3[1]
    }
    return obj
}


function queryURLparamsRegEs5(url) {
    let obj = {}
    let reg = /([^?=&]+)=([^?=&]+)/g
    url.replace(reg, function() {
        obj[arguments[1]] = arguments[2]
    })
    return obj
}


function queryURLparamsRegEs6(url) {
    let obj = {}
    let reg = /([^?=&]+)=([^?=&]+)/g
    url.replace(reg, (...arg) => {
        obj[arg[1]] = arg[2]
    })
    return obj
}



/**
 * @param {string} param Parameter to be added to the end of the url
 * @returns 
 */
function addParameterToURL(param) {
    let _url = location.href;
    _url += (_url.split('?')[1] ? '&' : '?') + param;
    return _url;
}

UUID#

function UUID() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4";
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
    s[8] = s[13] = s[18] = s[23] = "-";
 
    var UUID = s.join("");
    return UUID;
}


function UUID() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });

}


function UUID() {
    function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}


function uuid2(len, radix) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [],i;
    radix = radix || chars.length;
 
    if (len) {
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
    } else {
        var r;
        
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
        uuid[14] = '4';
 
        for (i = 0; i < 36; i++) {
            if (!uuid[i]) {
                r = 0 | Math.random() * 16;
                uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
            }
        }
    }
 
    return uuid.join('');
}
const listdata = [
    {
      id: 1,
      name: "Hello",
    },
    {
      id: 2,
      name: "HaHaha",
    },
    {
      id: 3,
      name: "Xiao Yang Hello",
    },
];

function fuzzyQuery(list, keyWord, arrtibute = "name") {
    const reg = new RegExp(keyWord);
    const arr = [];
    for (let i = 0; i < list.length; i++) {
    if (reg.test(list[i][arrtibute])) {
        arr.push(list[i]);
    }
    }
    return arr;
};

console.log(fuzzyQuery(listdata, "Hello", "name")); // [{id: 1, name: 'Hello'}, {id: 3, name: 'Xiao Yang Hello'}]

Array Flattening#

const arr = [
  {
    id: 1,
    name: 'node-1',
  },
  {
    id: 2,
    name: 'node-2',
    children: [
      {
        id: 3,
        name: 'node-3',
      },
      {
        id: 4,
        name: 'node-4',
        children: [
          {
            id: 5,
            name: 'node-5',
          },
        ],
      },
    ],
  },
];

/**
 * Flatten
 */
const result = arr.reduce(function (prev, current) {
  prev.push({
    id: current.id,
    name: current.name,
    parent: current.parentId,
  });
  current.children &&
    current.children.forEach((v) => {
      v.parentId = current.id;
      arguments.callee(prev, v);
    });
  return prev;
}, []);

const map = [
  {
    id: 1,
    name: 'node-1',
    parentId: undefined,
  },
  {
    id: 2,
    name: 'node-2',
    parentId: undefined,
  },
  {
    id: 3,
    name: 'node-3',
    parentId: 2,
  },
  {
    id: 4,
    name: 'node-4',
    parentId: 2,
  },
  {
    id: 5,
    name: 'node-5',
    parentId: 4,
  },
];

/**
 * Flatten to tree structure
 */
const result = map.reduce(function (prev, current, i, arr) {
  current.children = a = arr.filter((v) => v.parentId === current.id);
  if (!current.parentId) {
    prev.push(current);
  }
  return prev;
}, []);

function flatten(arr) {
    let result = [];
    for (let i = 0; i < arr.length; i++) {
        if (Array.isArray(arr[i])) {
            result = result.concat(flatten(arr[i]));
        } else {
            result.push(arr[i]);
        }
    }
    return result;
};

function flatMap(list = [], id: number) {
    return list.flatMap(({children, ...other}) => {
        return [other].concat(flatMap(children))
    })
}

Deduplication#

// Array object deduplication
const duplicateRemoval = edgesdata.filter((item) => !line.some((ele) => ele?.id === item?.id));

// Array deduplication [1,2,1,2,1,3,3,3]
function duplicateRemoval(arr) {
	const res = new Map();
	return arr.filter((arr) => !res.has(arr.id) && res.set(arr.id, 1));
}

// Array deduplication [1,2,1,2,1,3,3,3]
const duplicateRemoval = (arr) =>  [...new Set(arr)];

// Array deduplication and merging similar data
function handlerArrayMerge(value){
    const tempIds = [],newArrs = [];
    for(const item of value){
        if(!tempIds.includes(item.id)){
            tempIds.push(item.id);
            newArrs.push(item);
        }else{
            for(const ele of newArrs){
                if(ele.id === item.id){
                    ele.children = handlerArrayMerge(ele.children.concat(item.children));
                }
            }
        }
    }
    return newArrs;
}

Regular Expression Validation#

// Check if the string is in HTML format
function isHtml(str) {
   return /<[a-z]+\d?(\s+[\w-]+=("[^"]*"|'[^']*'))*\s*\/?>|&#?\w+;/i.test(str);
}

Number Processing#

const num = 12.34567;

// Keep 2 decimal places without rounding
Math.floor(num * 100) / 100 // Output result is 12.34

// Keep 2 decimal places, rounding
num.toFixed(2);             // Output result is 12.35

// Round to keep 2 decimal places (if not enough digits, use 0 to supplement)
function keepTwoDecimals(num) {
  let result = parseFloat(num);
  if (isNaN(result)) {
    // Parameter does not meet requirements
    return false;
  }
  result = Math.round(num * 100) / 100;
  let rt = result.toString();
  let pos = rt.indexOf('.');
  if (pos < 0) {
    pos = rt.length;
    rt += '.';
  }
  while (rt.length <= pos + 2) {
    rt += '0';
  }
  return rt;
}

keepTwoDecimals(124);       // Output result 124.00

Timer Handling#

/**
 * Timer timing, pause, continue
 */
class timerRecording {
  timerId = undefined;
  // Define a variable to record the time during pause
  pauseTime = 0;
  // Define a variable to record the timer start time
  startTime = 0;

  startTimer() {
    // If there is already a timer running, return directly
    if (this.timerId) {
      return;
    }

    // Record the timer start time
    this.startTime = Date.now();

    // Start the timer, executing the callback function every second
    this.timerId = setInterval(() => {
      // Calculate the elapsed time
      let elapsed = Date.now() - this.startTime + this.pauseTime;

      // Convert the elapsed time to seconds
      let seconds = parseInt(elapsed / 1000);

      // Display the formatted time in the current article's tag attribute
      document
        .getElementById('detail-content')
        ?.setAttribute('data-time', seconds);
    }, 1000);
  }

  // Pause the timer
  pauseTimer() {
    // If there is no timer running, return directly
    if (!this.timerId) {
      return;
    }

    // Clear the timer
    clearInterval(this.timerId);

    // Record the time during pause
    this.pauseTime += Date.now() - this.startTime;

    // Clear the timer ID
    this.timerId = null;
  }
  // Continue the timer
  continueTimer() {
    // If there is already a timer running, return directly
    if (this.timerId) {
      return;
    }

    // Record the timer start time
    this.startTime = Date.now();

    // Start the timer, executing the callback function every second
    this.timerId = setInterval(() => {
      // Calculate the elapsed time
      let elapsed = Date.now() - this.startTime + this.pauseTime;

      // Convert the elapsed time to seconds
      let seconds = parseInt(elapsed / 1000);

      // Display the formatted time in the current article's tag attribute
      document
        .getElementById('detail-content')
        ?.setAttribute('data-time', seconds);
    }, 1000);
  }
}

const timerRecord = new timerRecording();
export { timerRecord };
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.