2024 前端手撕代码 有限异步调用promise,实现自己的reduce方法,实现自己的map方法,实现自己的call,bing,apply方法,数组和对象去重

          目录​​​​​​​

有限异步调用promise

实现自己的reduce方法

实现自己的map方法

实现自己的call方法

实现自己的bind方法

实现自己的apply方法

数组去重(直接array.from+set)

对象去重(filter)


有限异步调用promise

1. fetchimage函数,每创建一个图像返回一个promise类型

function fetchimage(url){

return new Promise((resolve,reject)=>{

let x = new Image()
x.onload=function(){
resolve(x)
}
x.onerror=function(){

console.error('wrong')
}
x.src=url

})
}

2. limitload 函数

function limitload(func,limit,urls){

let sequence=urls.slice()
//将所有图像资源都复制到sequence
let promises=[]//其实这里是存图像序号的,应该维持limit个的大小

for(let i=0;i<limit && sequence.length;i++)
{
 let x = sequence.shift()
 const promise = func(x).then((data)=>{
console.log('load a image',data)
return i
})
promises.push(promise)

}

function next(){

if(sequence.length===0)
{
 return Promise.all(promises)
}

let x = sequence.shift()
const promise=func(x).then((data)=>{
console.log('load a image',data)
return next()
})
return Promise.race(promises).then((fast)=>{
promises[fast]=promise
})


}

return next()

}

测试数据: 

const imageUrls = [
      'https://copyright.bdstatic.com/vcg/creative/cc9c744cf9f7c864889c563cbdeddce6.jpg@h_1280',
      'https://inews.gtimg.com/om_bt/OHyQqgC_5oi4Vm0tlH49XvJzqNBHo2Zryxx5F_be5N2cIAA/1000',
      'https://inews.gtimg.com/om_bt/OGlQWfsaAoKkuCcMZ2o9IVEPqd-72DQy5EAN02XBHUwfYAA/641',
      'https://univs-news-1256833609.file.myqcloud.com/resource_files/cont_pub/I/AIJOI/J3SLIQIDP5BOND3A2T57W6BTOI.png',
      'https://img1.baidu.com/it/u=465289696,3068910287&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=1067'
   ];

   const limit = 2; // 最多同时加载两张图片
   
   limitLoad(imageUrls, fetchimage, limit)
      .then(() => {
         console.log('All images loaded successfully');
      })
      .catch((error) => {
         console.log('Error loading images:', error);
      });

完整代码:GitHub - Alicca-miao/asynchronous-calling-limited-promiseContribute to Alicca-miao/asynchronous-calling-limited-promise development by creating an account on GitHub.icon-default.png?t=N7T8https://github.com/Alicca-miao/asynchronous-calling-limited-promise

实现自己的reduce方法

Array.prototype.myreduce=function(fn,initialval){

//经常对某个数组归并求和
for(let i=0;i<this.length;i++)
{
  if(typeof initialval==='undefined')
  {
   initialval=fn(this[i],this[i+1],i+1,this)
//如果当前没有初始值,初始值就是数组的第一个元素

  }
else
initialval = fn(initialval,this[I],i,this)
//pre的值,当前的值,当前的index和指向的数组
}
return initialval

}


测试数据

let z = [1,2,3,4].myreduce(function(pre,cur,index,array){
    return pre+cur
  },0)
  console.log(z)//10
  

实现自己的map方法

Array.prototype.mymap=function(fn,context){
let arr=[]
this.forEach((item,index)=>{

arr.push(fn.call(context?context:this,item,index,this))

})
return arr
}

测试数据:

let z = arr2.mymap((item,index)=>{
      return item*2
    })
    console.log(z)

实现自己的call方法

Function.prototype.mycall=function(context){

//第一步判断this是否为函数

if(typeof this !=='function'){
	console.error('wrong')
	return
}
//如果context不存在用windows代替
let result = null
context=context || window
context.fn=this
let args = [...arguments].slice(1)
result = context.fn(...args)
//在context的前提下执行,但是默认是被调用的场景下执行也就是会在fn的上下文里执行所以想改变上下文到context
delete context.fn
return result
}

实现自己的bind方法

Function.prototype.mybind = function (context){
      if(typeof this !=='function'){
        console.error('wrong')
        return
      }
      let args=[...arguments].slice(1)
      let fn = this
      //这句是必须的后续调用的fn不然后面return function this会改变指向
return function Fn(){
  return fn.apply(this instanceof Fn? this:context,args.concat(...arguments))
}
    }

实现自己的apply方法

Function.prototype.myapply = function (context){
      if(typeof this !=='function')
      {
        console.error('wrong')
        return
      }
      let args = arguments[1]
      let result=null
      context.fn=this
      if(args){
        
      result= context.fn(...args)
      }
      else
   result= context.fn()
  delete context.fn
  return result
    }

数组去重(直接array.from+set)

let arr2=[2,2,3,4,2,2,55,3,55]
   function quchong(arr){
    return Array.from(new Set(arr2))
   }
   console.log(quchong(arr2))

//filter函数的使用:对于每个元素调用callback函数,如果返回值为true会被添加到新数组里否则不会

对象去重(filter)

function quchon(array,key){

let uset=new Set()
let newa = array.filter((item)=>{
if(uset.has(item[key]))
return false;
else
{
 uset.add(item[key])
return true
}

})
return newa

}

测试数据:

var resources = [
    { name: "张三", age: "18" },
    { name: "张三", age: "19" },
    { name: "张三", age: "20" },
    { name: "李四", age: "19" },
    { name: "王五", age: "20" },
    { name: "赵六", age: "21" }
  ]
  console.log(quchon(resources, 'name'));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值