# 高阶函数及 map、reduce、filter 的实现

2019/04/10 10:10

2020 开年国家经历了不少困难，最为凶猛的局势就是新型冠状病毒的蔓延，国务院最终决定春节假期延长至==2 月 2 号==；公司决定 3 - 7 号在家用 vpn 办公。10 号正式在职场上班；

## 函数

JavaScript 函数有两个支柱性的重要特性：一等函数和高阶函数

``````function multiplier(a, b) {
return a * b
}

let square = function(x) {
return x * x
}

// lambda 表达式（箭头函数）
let square = x => x * x
``````

## 高阶函数

``````function add(a) {
return function(b) {
return a + b
}
}
``````

``````function currying(fn, length) {
length = length || fn.length;
return function (...args) {
return args.length >= length
? fn.apply(this, args)
: currying(fn.bind(this, ...args), length - args.length)
}
}

const add = currying(function(a, b, c) {
console.log([a, b, c].reduce((a, b) => a + b))
})

``````

## map、reduce、filter

### map 的实现

``````function map(fn) {
let idx = -1,
len = this.length,
result = new Array(len)

while (++idx < len) {
result[idx] = fn(this[idx], idx, this)
}
console.log('myself')
return result
}
Array.prototype.map = map;
[1, 2, 3].map(ele => `#\${ele}#`)
// myself
// ["#1#", "#2#", "#3#"]
``````

### reduce 实现

``````function reduce(fn, accumulator) {
let idx = -1,
len = this.length

if (!accumulator && len > 0) {
accumulator = this[++idx]
}

while (++idx < len) {
accumulator = fn(accumulator, this[idx], idx, this)
}
console.log('myself')
return accumulator
}
Array.prototype.reduce = reduce;
[1, 2, 3].reduce((n, p) => n + p)
// myself
// 6

// 也可以指定第一个累计值
[1, 2, 3].reduce((n, p) => n + p, 100)
// myself
// 106
``````

### filter 的实现

``````function filter(fn) {
let idx = -1,
len = this.length
result = []

while (++idx < len) {
let value = this[idx]
if (fn(value, idx, this)) {
result.push(value)
}
}
console.log('myself')
return result
}
Array.prototype.filter = filter;
[1, 2, 3].filter(ele => ele >= 2)
// myself
// [2, 3]
``````

0
0 收藏

0 评论
0 收藏
0