面试官直呼内行!如何实现一个比较完美的reduce函数?

前端瓶子君

共 12195字,需浏览 25分钟

 · 2022-07-11

基本用法

reduce函数是js原生提供的用于处理数组结构的函数。

先来看一下MDN中的介绍:

reduce() 方法对数组中的每个元素按序执行一个由用户提供的 reducer 函数,每一次运行 reducer 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。

参数

  1. callbackFn 一个 reducer 函数,包含四个参数:
  • previousValue:上一次调用 callbackFn时的返回值。在第一次调用时,若指定了初始值 initialValue,其值则为 initialValue,否则为数组索引为 0 的元素 array[0]
  • currentValue:数组中正在处理的元素。在第一次调用时,若指定了初始值 initialValue,其值则为数组索引为 0 的元素 array[0],否则为 array[1]
  • currentIndex:数组中正在处理的元素的索引。若指定了初始值 initialValue,则起始索引号为 0,否则从索引 1 起始。
  • array:用于遍历的数组。
  1. initialValue 可选 作为第一次调用 callback 函数时参数 previousValue 的值。若指定了初始值 initialValue,则 currentValue 则将使用数组第一个元素;否则 previousValue 将使用数组第一个元素,而 currentValue 将使用数组第二个元素。

reduce函数功能是非常强大的适用于非常多的场景:

比如使用reduce函数实现累加:

  let total = [ 0123 ].reduce(
    ( previousValue, currentValue ) => previousValue + currentValue,
    0
  )
  // 6

生成新数组:

  let total = [ 0123 ].reduce(
    function (pre, cur{
      pre.push(cur + 1)
      return pre
    },
    []
  )
  // [1, 2, 3, 4]

等等.....

那么问题来了,如何手写实现一个reduce函数呢?

实现基础版本

根据文档可知,reduce函数接受一个运行函数和一个初始的默认值

   /**
    *
    * @param {Array} data 原始数组
    * @param {Function} iteratee 运行函数
    * @param {Any} memo 初始值
    * @returns {boolean} True if value is an FormData, otherwise false
    */

  function myReduce(data, iteratee, memo{
      // ...
  }

接下来实现基本功能

reduce函数的重点就是要将结果再次传入执行函数中进行处理

  function myReduce(data, iteratee, memo{
   for(let i = 0; i < data.length; i++) {
    memo = iteratee(memo, data[i], i, data)
   }
   return memo
  }

需求一:增加this绑定

其实reduce函数可以指定自定义对象绑定this

在这里可以使用call对函数进行重新绑定

  function myReduce(data, iteratee, memo, context{
   // 重置iteratee函数的this指向
   iteratee = bind(iteratee, context)
  
   for(let i = 0; i < data.length; i++) {
    memo = iteratee(memo, data[i], i, data)
   }
   return memo
  }
  
  // 绑定函数 使用call进行绑定
  function bind(fn, context{
    // 返回一个匿名函数,执行时重置this指向
    return function(memo, value, index, collection{
      return fn.call(context, memo, value, index, collection);
    };
  }
  

需求二:增加对第二个参数默认值的支持

reduce函数的第三个参数也是可选值,如果没有传递第三个参数,那么直接使用传入数据的第一个位置初始化

  function myReduce(data, iteratee, memo, context{
   // 重置iteratee函数的this指向
   iteratee = bind(iteratee, context)
   // 判断是否传递了第三个参数
   let initial  = arguments.length >= 3// 新增
   // 初始的遍历下标
   let index = 0 // 新增
  
   if(!initial) { // 新增
    // 如果用户没有传入默认值,那么就取数据的第一项作为默认值
    memo = data[index] // 新增
    // 所以遍历就要从第二项开始
    index += 1 // 新增
   }
  
   for(let i = index; i < data.length; i++) { // 修改
    memo = iteratee(memo, data[i], i, data)
   }
   return memo
  }
  
  // 绑定函数 使用call进行绑定
  function bind(fn, context{
    return function(memo, value, index, collection{
      return fn.call(context, memo, value, index, collection);
    };
  }
  

需求三:支持对象

js原生的reduce函数是不支持对象这种数据结构的,那么如何完善我们的reduce函数呢?

其实只需要取出对象中所有的key,然后遍历key就可以了

 function myReduce(data, iteratee, memo, context{
 
   iteratee = bind(iteratee, context)
   // 取出所有的key值
   let _keys = !Array.isArray(data) && Object.keys(data) // 新增
   // 长度赋值
   let len = (_keys || data).length // 新增
 
   let initial  = arguments.length >= 3;
   let index = 0
  
   if(!initial) {
    // 如果没有设置默认值初始值,那么取第一个值的操作也要区分对象/数组
    memo = data[ _keys ? _keys[index] : index] // 修改
    index += 1
   }
  
   for(let i = index; i < len; i++) {
    // 取key值
    let currentKey = _keys ? _keys[i] : i // 新增
    memo = iteratee(memo, data[currentKey], currentKey, data) // 修改
   }
   return memo
  }
  
  function bind(fn, context{
    return function(memo, value, index, collection{
      return fn.call(context, memo, value, index, collection);
    };
  }
  

需求四:reduceRight

其实以上的内容已经是一个比较完整的reduce函数了,最后一个扩展内容是reduceRight函数,其实reduceRight函数的功能也很简单,就是在遍历的时候倒序进行操作,例如:

 let total = [ 0, 1, 2, 3 ].reduce(
    function (pre, cur) {
      pre.push(cur + 1)
      return pre
    },
    []
  )
  
  // [1, 2, 3, 4]

其实实现这个功能也非常简单,只需要初始操作的值更改为最后一个元素的位置就可以了:

// 加入一个参数dir,用于标识正序/倒序遍历
function myReduce(data, iteratee, memo, context, dir//修改

  iteratee = bind(iteratee, context)
  let _keys = !Array.isArray(data) && Object.keys(data)
  let len = (_keys || data).length

  let initial  = arguments.length >= 3;

  // 定义下标
  let index = dir > 0 ? 0 : len - 1 // 修改
 
  if(!initial) {
   memo = data[ _keys ? _keys[index] : index]
   // 定义初始值
   index += dir // 修改
  }
  // 每次修改只需步进指定的值
  for(;index >= 0 && index < len; index += dir) { // 修改
   let currentKey = _keys ? _keys[index] : index
   memo = iteratee(memo, data[currentKey], currentKey, data)
  }
  return memo
 }
 
 function bind(fn, context{
   if (!context) return fn;
   return function(memo, value, index, collection{
     return fn.call(context, memo, value, index, collection);
   };
 }

调用的时候直接传入最后一个参数为1 / \-1即可

 myReduce([1234], function(pre, cur{
     console.log(cur)
 }, [], 1)
 
 myReduce([1234], function(pre, cur{
     console.log(cur)
 }, [], -1)

最后将整个函数进行重构抽离成为一个单独的函数:

 function createReduce(dir{
     function reduce({
   // ....
     }
 
     return function({
   return reduce()
     }
 }

最后最终的代码如下:

 function createReduce(dir{
 
     function reduce(data, fn, memo, initial{
         let _keys = Array.isArray(data) && Object.keys(data),
             len = (_keys || data).length,
             index = dir > 0 ? 0 : len - 1;

         if (!initial) {
             memo = data[_keys ? _keys[index] : index]
             index += dir
         }

         for (; index >= 0 && index < len; index += dir) {
             let currentKey = _keys ? _keys[index] : index
             memo = fn(memo, data[currentKey], currentKey, data)
         }
         return memo
     }


     return function (data, fn, memo, context{
         let initial = arguments.length >= 3
         return reduce(data, bind(fn, context), memo, initial)
     }
 }

 function bind(fn, context{
     if (!context) return fn;
     return function (memo, value, index, collection{
         return fn.call(context, memo, value, index, collection);
     };
 }

 let reduce = createReduce(1)
 let reduceRight = createReduce(-1)

而这种实现方式也是underscore.js所实现的reduce函数的方式。

写在最后 ⛳

未来可能会更新实现mini-vue3javascript基础知识系列,希望能一直坚持下去,期待多多点赞🤗🤗,一起进步!🥳🥳


关于本文

来自:pino

https://juejin.cn/post/7113743909452251167


最后


欢迎关注【前端瓶子君】✿✿ヽ(°▽°)ノ✿
回复「算法」,加入前端编程源码算法群,每日一道面试题(工作日),第二天瓶子君都会很认真的解答哟!
回复「交流」,吹吹水、聊聊技术、吐吐槽!
回复「阅读」,每日刷刷高质量好文!
如果这篇文章对你有帮助,在看」是最大的支持
 》》面试官也在看的算法资料《《
“在看和转发”就是最大的支持


浏览 11
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报