首页 > 编程语言 >JavaScript手写函数

JavaScript手写函数

时间:2022-09-26 19:11:07浏览次数:52  
标签:function return 函数 JavaScript pid let 手写 id fn

 

// url的queryString转成对象
function queryStr2Obj(url) {
    const query = {};
    const search = url.split('?')[1];
    if (!search) {
        return {}
    }
    search.split('&').forEach(item => {
        let [ key, value] = item.replace('=', ':').split(':');
        query[key] = decodeURIComponent(value);

    });
    return query;
}

// list数组转tree数组
const currentArray = [
  {id:"01", name: "张大大", pid:"", job: "项目经理"},
  {id:"02", name: "小亮", pid:"01", job: "产品leader"},
  {id:"03", name: "小美", pid:"01", job: "UIleader"},
  {id:"04", name: "老马", pid:"01", job: "技术leader"},
  {id:"05", name: "老王", pid:"01", job: "测试leader"},
  {id:"06", name: "老李", pid:"01", job: "运维leader"},
  {id:"07", name: "小丽", pid:"02", job: "产品经理"},
  {id:"08", name: "大光", pid:"02", job: "产品经理"},
  {id:"09", name: "小高", pid:"03", job: "UI设计师"},
  {id:"10", name: "小刘", pid:"04", job: "前端工程师"},
  {id:"11", name: "小华", pid:"04", job: "后端工程师"},
  {id:"12", name: "小李", pid:"04", job: "后端工程师"},
  {id:"13", name: "小赵", pid:"05", job: "测试工程师"},
  {id:"14", name: "小强", pid:"05", job: "测试工程师"},
  {id:"15", name: "小涛", pid:"06", job: "运维工程师"}
];

function list2tree(list, pid){
  let children = list.filter(item => item.pid == pid);
  return children.map(item => {
    item.children = list2tree(list, item.id);
    return item;
  })
}
// tree数组转list数组
function tree2list(tree){
  const list = [], queue = [...tree];
   while(queue.length){
     let { children, ...node } = queue.shift();
     if(children){
       queue.push(...children)
     }
     list.push(node)
   }
  return list;
}
// 多维数组,每每元素组合,不重复
/*
* 如: arr =  [[1,2],[3,4]]  => combination(arr) => [[1,3],[1,4],[2,3],[2,4]]
*/
function combination(arr){
  const ary = [];
  const store = [];
  const fn = function (i = 0){
    for(let j = 0; j<arr[i].length;j++){
     if(i < arr.length - 1){
        store[i] = arr[i][j];
        fn(i+1)
     }else{
       ary.push([...store, arr[i][j]])
     }
    }
  }
  fn();
  
  return ary;
}
// 函数柯里化(思路:递归收集参数,参数刚好时调用原函数)
function curry(fn, args = []){
  
  return (...arg) => {
    let _arg = args.concat(arg)
    if(_arg.length != fn.length){
      return curry(fn, _arg)
    }else{
      return fn(..._arg)
    }
  }
}
// 节流
function throttle(fn, delay) {
  // 重置定时器
  let timer = null;
  // 返回闭包函数
  return function () {
    // 记录事件参数
    let args = arguments;
    // 如果定时器为空
    if (!timer) {
      // 开启定时器
      timer = setTimeout(() => {
        // 执行函数
        fn.apply(this, args);
        // 函数执行完毕后重置定时器
        timer = null;
      }, delay);
    }
  }
}
// 防抖
function debounce(fn, delay = 500) {
  // timer是一个定时器
  let timer = null;
  // 返回一个闭包函数,用闭包保存timer确保其不会销毁,重复点击会清理上一次的定时器
  return function () {
    // 保存事件参数,防止fn函数需要事件参数里的数据
    let arg = arguments;
    // 调用一次就清除上一次的定时器
    clearTimeout(timer);
    // 开启这一次的定时器
    timer = setTimeout(() => {
      // 若不改变this指向,则会指向fn定义环境
      fn.apply(this, arg);
    }, delay)
  }
}
// call
function mycall(that, ...args){
  that = that == null ? window : new Object(that)
  that.fn = this;
  that.fn(...args);
  delete that.fn;
}
Function.prototype.mycall = mycall
// apply
function myapply(that, args){
  that = that == null ? window : new Object(that)
  that.fn = this;
  that.fn(...args);
  delete that.fn;
}
Function.prototype.myapply = myapply
// bind
function mybind(that) {
  let fn = this;
  return function(...args){
    fn.apply(that, args);
  }
}
Function.prototype.mybind = mybind 
// new
function myNew(fn, ...args){
  let obj = Object.create(fn.prototype);
  fn.apply(obj, args);
  return obj;
}

// instanceof实现
function instanceOf(origin, target) {
      
    while(1){
       if(origin.__proto__ == target.prototype){
         return true
       } 
       if(origin.__proto__ == null){
         return false
       }
      origin = origin.__proto__
    }
}
// 数组乱序
function shuffle(arr) {
    let len = arr.length;
    for (let i = 0; i < len - 1; i++) {
        let index = parseInt(Math.random() * (len - i));
        let temp = arr[index];
        arr[index] = arr[len - i - 1];
        arr[len - i - 1] = temp;
    }
    return arr;
}
// 随机字串
function randomString(len) {
  len = len || 8;
  let $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  let maxPos = $chars.length;
  let str = '';
  for (let i = 0; i < len; i++) {
    str += $chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return str;
}

  

标签:function,return,函数,JavaScript,pid,let,手写,id,fn
From: https://www.cnblogs.com/shaoyunfeng93/p/16732044.html

相关文章

  • Oracle常用函数
    目录Oracle常用函数1、时间函数1.1、获取当月第一天1.2、当月最后一天2、切割函数substrOracle常用函数1、时间函数1.1、获取当月第一天selectto_char(trunc(add_mon......
  • 18. NumPy统计函数
    1.前言NumPy提供了许多统计功能的函数,比如查找数组元素的最值、百分位数、方差以及标准差等。2.numpy.amin()和numpy.amax()这两个函数用于计算数组沿指定轴的最......
  • 分治法求解幂函数
    #include<iostream>usingnamespacestd;floatpower(floatx,inty){floattemp;if(y==0)return1;temp=power(x,y/2);if(y%2==0)......
  • 手写vue-router核心原理
    最近也在观察vue3新特性,抽空玩一玩嵌套路由的vue-router,直接上代码项目目录结构代码展示app.vue<template><divid="app"><div><router-linkto="/"......
  • JavaScript超大文件上传和断点续传的实现
    ​ 1 背景用户本地有一份txt或者csv文件,无论是从业务数据库导出、还是其他途径获取,当需要使用蚂蚁的大数据分析工具进行数据加工、挖掘和共创应用的时候,首先要将本地文......
  • javascript: 自定义鼠标拖动的滑块slider(chrome 105.0.5195.125)
    一,js代码<html><head><metacharset="utf-8"/><title>测试</title></head><bodyonmousemove="divmousemoving()"onMouseUp="divmouseup()"><divstyle=......
  • python-模块-模块导入之其它函数
    1.dir()dir()函数一个排好序的字符串列表,内容是一个模块里定义过的名字。返回的列表容纳了在一个模块里定义的所有模块,变量和函数1.1dir示例定义一个模块#coding-......
  • C++ 导入动态链接库DLL 中的函数
    C++导入动态链接库DLL中的函数声明头文件<windows.h>,利用windows库进行DLL的加载#include<windows.h>然后用typedef定义一个指针函数类型typedefvoid(**fun),这......
  • vue3中的hook自定义函数
    1.建立hook文件夹,在hook文件夹里面建立useAxios.ts文件,内容如下:import{ref}from'vue';importaxiosfrom'axios';exportdefaultfunction<T>(url:string,m......
  • 波函数坍缩算法
    https://www.bilibili.com/video/BV1k5411u7t7/?spm_id_from=333.788.top_right_bar_window_history.content.click&vd_source=426e9399caf4b3d209b6ac8487de530bhttps://......