js-读书笔记-函数式编程-for抽象

// 函数式编程
const _ = require('../lib/underScore.js')

// let lyrics = []
// for (let bottles = 10; bottles > 0; bottles--) {
//   lyrics.push(bottles + '墙上有啤酒')
//   lyrics.push(bottles + '多少瓶啤酒')
//   // lyrics.push('take one down, pass it around')
//   lyrics.push('拿一个下来,分给大家')
//   if(bottles > 1) {
//     lyrics.push((bottles - 1) + '墙上还有的啤酒')
//   } else {
//     lyrics.push('墙上没有啤酒了')
//   }
// }
// console.log(lyrics)

// 抽象for循环内容
function LyricSegment(n) {
  return _.chain([])
    .push(n + '墙上有啤酒')
    .push(n + '多少瓶啤酒')
    .push('拿一个下来,分给大家')
    .tap(function(lyrics) {
      if(n > 1 ) {
        lyrics.push((n - 1) + '墙上还有的啤酒')
      } else {
        lyrics.push('墙上没有啤酒了')
      }
    })
    .value()
}

// 使用reduce取待for循环
function song(start, end, lyricsGen) {
  let ary = _.range(start, end, -1)
  return ary.reduce(function(acc, n) {
    return acc.concat(lyricsGen(n))
  }, [])
}
let l = song(10, 0, LyricSegment)
console.log(l)






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值