lambda+reduce的一句艰深代码

时间:2022-04-27
本文章向大家介绍lambda+reduce的一句艰深代码,主要内容包括一句话一脸懵逼、工程学作文: 单元 - 集成、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

一句话一脸懵逼

某天晚上看到一句lambda+reduce 组合的代码,看的头都炸了,愣是没看懂,不过也可能因为稀疏的脑神经经过一天的摧残已经运转不动了,这两天拿出来一看,一不留神理通了。

代码如下:

// lambda & reduce & simple recursive
const flatten = arr => arr.reduce(
	(a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []
);

第一眼看到这句代码我的心情是懵逼的,不知道路人是什么感觉,如果你一眼扫过能看懂,我只能膜拜一下:大神!至少具备js的神格。

工程学作文: 单元 - 集成

先分别解读 lambda & reduce ,然后再整体剖析。。。

lambda

lambda表达式,是实现函数式编程、管道(pipe)结构、回调函数等的一快捷方式,它可以使代码变简洁优雅,同时,它也会使代码变得更晦涩。

书写格式:

(a,b...) => exp
//相当于
function(a,b...){
	return exp...
}

/**
 * 可以简单理解为 
 * 左侧(a,b...)为参数列表 
 * 右侧exp 表达式为函数所要执行的动作,
 * 这个动作的执行结果作为返回数据
 */

reduce

reduce是js数组操作的一个函数,在做统计计量的时候会经常用到,在任何有关于reduce的介绍的地方,都会称之为一个累加器。

 /**
  * reduce的调用方式
  * callback为回调函数, initialValue 可选参数  初始值
  */
 arr.reduce(callback, initialValue);

/**
 * 回调函数包括四个可选参数
 * ① previousValue 上一次调用 callback返回的值, 如果当前是第一次调用,则为initialValue的值
 *   如果调用reduce的时候没有传入initialValue的值,则为数组下标为0的值
 * ② currentValue & currentIndex 当前数组中被处理的值与其下标 ,如果没有传入initialValue的值,下标从1开始
 *   (下标为0的值已被previousValue占据)
 * ③ array 调用reduce的数组
 */
 var callback=function(previousValue, currentValue, currentIndex, array){
 	// do sth...
 };

为了加深对这个函数的理解(总之以一切方式减少懵逼度),自我实现如下(省略测试过程):

Array.prototype.myReduce=function(callback,initialValue){
	if(initialValue==undefined){
		previousValue= this[0];
		currentValue = this[1];
		currentIndex = 1;
	} else{
		previousValue= initialValue;
		currentValue = this[0];
		currentIndex = 0;
	}

	for(var i=currentIndex; i<this.length;i++){
		previousValue=callback(previousValue,currentValue,currentIndex,this);
		currentValue =this[i+1];
		currentIndex =i+1;
	}

	return previousValue;
};

如果你想查看有关 reduce 的详细介绍,请点击:

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce_clone

回归总体

// 原始代码
// const flatten = arr => arr.myReduce(
// 	(a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []
// );

// 拆除lambda 得 (这里可以看到,flatten 算法实际上返回的是一个数组)
var flatten=function(arr){
	return arr.myReduce(
		function(a, b){
			return a.concat( Array.isArray(b) ? flatten(b) : b );
		},[]
	);
};

/**
 * 如果你看懂了myReduce的逻辑, 那么 a,b 的意义应该不难于理解
 * a(previousValue), 因为reduce传入了initialValue [] 所以首次调用回调 a == []
 * b(currentValue) , 首次调用下标为 0
 *
 * a.concat( Array.isArray(b) ? flatten(b) : b )
 * 循环遍历数组中的每个元素, 如果是数组 则将执行过flatten算法后得到的数组连接入a ,否则 将其连接入a
 *
 * 回调函数将 类型为数组的数组元素 连接入上层数组,实际上是在降维
 * flatten算法通过reduce的数组循环遍历和自递归实际上是在将多维数组化为一维 
 */

下面来做两个测试:

var test1 = [[0, 1], [2, 3], [4, 5]];
var test2 = [0, [1, [2, [3, [4, [5]]]]]];

console.log(flatten(test1));
console.log(flatten(test2));

结果:

路过老铁 如果对算法感兴趣的话,欢迎一起来 抱拳!