JS Array.reduce 实现 Array.map 和 Array.filter

继上一篇 Array.prototype.reduce 后,我立志要好好学习。琢磨了很久,再加上最近看了几篇"JS 函数式编程"的文章和书籍后,然后有感而发写下了这篇文章。

Array.prototype.map 方法相信大家都用的很熟悉了,同时我也相信很多人已经自己实现了 map 函数。没有实现过自己的map ? 没关系,我们先用for 循环来实现下。

  Array.prototype.selfMap = function () {
      const ary = this
      const result = []
      const [ fn, thisArg ] = [].slice.call(arguments)
      if (typeof fn !== 'function') {
        throw new TypeError(fn + 'is not a function')  
      }
      for (let i = 0; i < ary.length; i++) {
        result.push(fn.call(thisArg, ary[i], i, ary))
      }
      return result
  }
  
  const a = new Array(1, 2, 3, 4)
  a.selfMap(item => item + 1) // [ 2, 3, 4, 5 ]
复制代码

实现了自己的map,还不是美滋滋。

但是,这和本文没有半点关系,因为我是要用reduce实现map啊???

众所周知,map函数需要传一个函数的,还有一个可选的this参数,但是我发现第二个参数大家很少用到,也不怎么注意,我也是这样。

[1, 2, 3].map(function(item) {
    console.log(this)
    return item
}, { msg: 'mapping' })
复制代码

上面?这段代码块不仅会返回一个新的数组,还会在控制台打印三次

 { msg: 'mapping' }
复制代码

有图有真相?

可能有的小伙伴在验证我上面的例子时,会使用箭头函数,然后发现总是打印window,就是下面这样?

然后心里暗道“无耻小儿,竟敢骗我”。心里苦啊,箭头函数在声明时就绑定了它外层的this(此例的thiswindow,而且还改变不了, 也就是说{ msg: 'mapping' }相当于白传了)?

似乎废话有点多额,那我们先用reduce来实现map吧(默认运行环境支持Array.prototype.reduce,如果不支持的话,那还写个?)

    // 这次不把方法写在Array的原型上
    const reduceMap = (fn, thisArg /*真想去掉thisArg这个参数*/ ) => {
        return (list) => {
            // 不怎么愿意写下面这两个判断条件
            if (typeof fn !== 'function') {
                throw new TypeError(fn + 'is not a function')  
            }
            if (!Array.isArray(list)) {
                throw new TypeError('list must be a Array')
            }
            if (list.length === 0) return []
            return list.reduce((acc, value, index) => {
                return acc.concat([ fn.call(thisArg, value, index, list) ])
            }, [])
        }
    }
    
    // 来使用下怎么样?
    
    reduceMap(x => x + 1)([ 1, 2, 3 ]) // [ 2, 3, 4 ]
    
    const mapAry1 = reduceMap(function(item) {
        console.log(this)
        return item + 1
    }, { msg: 'mapping' })([ 1, 2, 3 ]) 
    // [ 2, 3, 4 ] 
    // logging { msg: 'mapping' } three times
复制代码

?实现的原理相信大家应该都懂吧。

打铁当趁热,继续来实现filter吧。

  • for 循环实现版
Array.prototype.selfFilter = function () {
    const ary = this
    const result = []
    const [ fn , thisArg ] = [].slice.call(arguments)
    
    if (typeof fn !== 'function') {
        throw new TypeError(fn + 'is not a function')  
    }
    
    for (let i = 0; i < ary.length; i++) {
        if (fn.call(thisArg, ary[i], i, ary)) {
            result.push(ary[i])
        }
    }
    return result
}

const a = new Array(1, 2, 3)
a.selfFilter(item => item % 2 === 0) // [ 2 ]
a.selfFilter(function (item) {
    console.log(this)
    return item % 2 === 0
}, {})
// [ 2 ]
// logging {} three times
复制代码
  • reduce 实现版
// 同map, 不定义在Array的原型上
const reduceFilter = (fn, thisAry /* thisAry知不知你好讨厌啊 */ )  => {
    return (list) => {
        if (typeof fn !== 'function') {
            throw new TypeError(fn + 'is not a function')  
        }
        if (!Array.isArray(list)) {
            throw new TypeError('list must be a Array')
        }
        if (list.length === 0) return []
        return list.reduce((acc, value, index) => {
            return fn.call(thisAry, value, index, list) ? acc.concat([ value ]) : acc
        }, [])
    }    
}

reduceFilter(x => x % 2 === 0)([ 1, 2, 3 ]) // [ 2 ]

复制代码

文章里掺杂了些许函数式编程里面的东西,因为我也才开始学函数式编程不久,就不在大佬们面前献丑了。如果文章里有哪里写的不对或者不够准确,亦或者是觉得有写的不好的地方,烦请各位指正,也让我改正。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值