手写常用函数源码系列

一..扁平化数组
   

  • Array.prototype.flat() 用于将嵌套的数组扁平化,变成一维的数组。该方法返回一个新数组,对原数据没有影响。
  • 不传参数时,默认扁平化一层,可以传入一个整数,表示想要扁平化的层数。
  • 传入 <=0 的整数将返回原数组,不扁平化
  • Infinity 关键字作为参数时,无论多少层嵌套,都会转为一维数组
  • 如果原数组有空位,Array.prototype.flat() 会跳过空位。

   1. 利用  数组的 reduce  方法;

 function flat( arr,depth){
        return   depth>0 ?  arr.reduce((acc,cur)=>{
              if (Array.isArray(cur)){
             return  [...acc,...flat(cur,depth-1)]
              }    
         return [...acc,cur];

},[]):arr

}

var test = ["a", ["b", "c"], ["d", ["e", ["f"]], "g"]];

 flat(test,1)

  // ["a", "b", "c", "d", Array(2), "g"]


 // 变形题目考察原型方法, 编写test.flatDeep(depth)


Array.prototype.flatDeep=function(depth){
        return   depth>0 ?  this.reduce((acc,cur)=>{
              if (Array.isArray(cur)){
             return  [...acc,...cur.flatDeep(depth-1)]
              }    
         return [...acc,cur];

},[]):arr
}

test.flatDeep(1)// 


二  数组去重 
  1. es6   方法 

function unique(arr){
     return  Array.from(new Set(arr))
     //   return [...new Set(arr)]
}

2. 利用hash  表   reduce   方法封装  数组元素n    时间复杂度O(n), 空间复杂度O(n)

function unique (arr){
    const map=new Map();
  return  arr.reduce((acc,cur)=>{
         if(!map.has(cur)){
           map.set(cur,cur);
            acc.push(cur);
          }
     return acc ;

},[])

}


 var test = [1 ,'1',0,NaN,null,undefined,null ];

unique(test);
// [1, "1", 0, NaN, null, undefined]

 3.   函数组合compose  ;

const compose  = (...fns)=>(args)=>fns.reduceRight((acc,cur)=>cur(acc),args);
// 形成一个由右到左执行的函数流;

如果希望函数从左向右执行;

// const compose  = (...fns)=>(args)=>fns.reduce((acc,cur)=>acc(cur),args);

4. 函数柯里化

 const curry =(fn)=>(...args)=>arg.length===fn.length?fn.call(null,...args):fn.bind(null,...args);

5.实现new  关键字

 function _new(fn,...rest){
     const tempObj = Object.create(fn.prototype);
     const fnResult  = fn.call(tempObj,...rest);
    return   fnResult instanceof Object  ? fnResult : tempObj
    
}

6. 实现es 5 继承

function ParentFn(name,age){
      this.color='red'
      this.name=name;

}
 ParentFn.prototype.sayName= function(){
      console.log(this.name);
   }

function ChildFn(parentName,childName){
      ParentFn.call(this, parentName);
      this.childName = childName;
     
}

  ChildFn.prototype=Object.create(ParentFn.protoType);

   ChildFn.prototype.constructor= ChildFn;




7. 实现数组的map方法;(回调函数的this)

Array.prototype.myMap=function(fn,context){
     const arr=Array.prototype.slice(this);
     const mapResult = [];
     for(let i =0;i<arr.length;i++){
        mapResult.push(fn.call(context,arr[i],i,this));
     }
     return mapResult;
     }







 




 
    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值