本文首发于个人博客 https://maclaren0920.github.io
javascript高阶函数 - 万能的reduce
javascript作为一门原生支持函数式编程的语言,在数组中有许多丰富的API方法,如forEach、filter、map、some、every、find、findIndex等。但是有一个方法却能实现以上方法所有的功能,那就是万能的<font color='red'>reduce</font>。
首先我们先看下reduce的语法:
arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
reduce共接收两个参数,一个是回调函数,一个是初始值(可选),回调函数共接收4个参数:
- accumulator 累计器
- current 当前值
- 当前索引
- 源数组
reduce会为数组中的每一项依次执行callback,并且会将callback执行完返回的累计值累计到accumulator参数中,等所有callback执行完毕再将accumulator返回。
下面我们就用reduce来实现以上所有的方法。
forEach
const arr = [1, 2, 3];
const forEach = (arr, callback) => {
arr.reduce((pre, current, index, array) => {
callback(current, index, array);
}, 0);
}
forEach(arr, (item, index, array) => {
console.log(`item`, item) // 1, 2, 3
console.log(`index`, index) // 0, 1, 2
console.log(`array`, array) // [1, 2, 3]
});
filter
const arr = [1, 2, 3];
const filter = (arr, callback) => {
return arr.reduce((pre, current, index, array) => {
const ret = callback(current, index, array);
if (ret) {
pre.push(current);
}
return pre;
}, []);
}
const result = filter(arr, (item) => {
return item > 1;
});
console.log(`result`, result); // [2, 3]
map
const arr = [1, 2, 3];
const map = (arr, callback) => {
return arr.reduce((pre, current, index, array) => {
const ret = callback(current, index, array);
pre.push(ret);
return pre;
}, []);
}
const result = map(arr, (item) => {
return item * 100;
});
console.log(`result`, result); // [100, 200, 300]
some
const arr = [1, 2, 3];
const some = (arr, callback) => {
return arr.reduce((pre, current, index, array) => {
const ret = callback(current, index, array);
if (ret) {
pre = true;
}
return pre;
}, false);
}
const result = some(arr, (item) => {
return item > 2;
});
console.log(`result`, result); // true
every
every有点不一样,需要一个中间变量存储以下状态。
const arr = [1, 2, 3];
const every = (arr, callback) => {
let flag = true;
const bool = arr.reduce((pre, current, index, array) => {
const ret = callback(current, index, array);
if (!ret) {
flag = false;
}
return flag;
}, false);
return bool;
}
const result = every(arr, (item) => {
return item > 2;
});
console.log(`result`, result); // false
find
const find = (arr, callback) => {
return arr.reduce((pre | null, current, index, array) => {
const ret = callback(current, index, array);
if (ret) {
pre = current;
}
return pre;
}, null);
}
const result = find(arr, (item) => {
return item === 3;
});
console.log(`result`, result); // 3
findIndex
const findIndex = (arr, callback) => {
return arr.reduce((pre, current, index, array) => {
const ret = callback(current, index, array);
if (ret) {
pre = index;
}
return pre;
}, -1);
}
const result = find(arr, (item) => {
return item === 3;
});
console.log(`result`, result); // 2
以上就是reduce对所列举方法中所有的实现,这就是reduce的强大之处。上述示例只是为了体现reduce的强大与灵活之处,在实际开发中,我们并不会这样去使用。
那么reduce具体在哪些地方有合适的使用呢,可以看看以下几个常见的示例。
求和
const subjectSummary = [
{id: 1, subject: '语文', score: 86},
{id: 2, subject: '数学', score: 93},
{id: 2, subject: '英语', score: 95},
];
以上数组中,对score字段进行求和:
const scoreSum = subjectSummary.reduce((pre, current) => {
return pre + current.score;
}, 0);
分组
const menuGroup = [
{id: 1, name: '用户中心',type: 1},
{id: 2, name: '设置', type: 2},
{id: 3, name: '消息中心', type: 2},
{id: 4, name: '我的', type: 1},
];
以上数组中是通过后端接口返回的用户菜单数据,我们需要通过type字段来进行分组,type为1的在主菜单中显示,type为2的在侧边栏显示。
const menuMap = menuGroup.reduce((pre, current) => {
if (current.type === 1) {
pre.menuList.push(current);
}
if (current.type === 2) {
pre.subMenuList.push(current);
}
return pre;
}, {menuList: [], subMenuList: []});
统计字符串出现次数
const str = 'aabdddeffghhhhyyy';
const countMapper = str1.split('').reduce((pre, current) => {
if (pre.hasOwnProperty(current)) {
pre[current] += 1;
} else {
pre[current] = 1;
}
return pre;
}, {});
数组去重
const arr = [1, 2, 3, 2, 3, 1, 8, 5];
const newArr = arr.reduce((pre, current) => {
if (!pre.includes(current)) {
pre.push(current);
}
return pre;
}, []);
顺序执行promise
const createPromise = (timeout) => {
return new Promise((resolve) => {
setTimeout(() => {
console.log(`timeout===>`, timeout);
resolve();
}, timeout);
});
}
const promiseArr = [createPromise.bind(null, 1000), createPromise.bind(null, 2000), createPromise.bind(null, 3000)];
const runPromiseInSQueue = (arr) => {
return arr.reduce((prePromise, currentPromise) => prePromise.then(currentPromise), Promise.resolve());
}
const p = runPromiseInSQueue(promiseArr);
p.then(() => {
console.log(`执行完成...`)
});
组合函数(compose)
redux中compose组合函数的实现:
function compose(...funcs) {
if (funcs.length === 0) {
return arg => arg
}
if (funcs.length === 1) {
return funcs[0]
}
return funcs.reduce((a, b) => (...args) => a(b(...args)))
}
以上是reduce方法比较常见的几个使用场景,还有更多的使用场景需要你去尝试和挖掘。
总结
通过以上对javascript几个高阶函数的实现和上述几个示例的运用,我们总结出以下几点:
- reduce可以返回任何你需要的数据类型
- callback中的执行逻辑和返回值完全由使用者来决定和控制
- 灵活运用reduce可以使业务更加聚合,并且减少许多中间变量
参考
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce