js-读书笔记-函数式编程-流

import _ from 'underscore'
import Utils from '../../lib/utils.js'
function pipeline(seed, ...args) {
  return args.reduce(function(l, r) {
    return r(l)
  }, seed) 
  // 当args为空数组的时候,直接返回初始值seed
}
console.log(pipeline())
console.log(pipeline(42))
console.log(pipeline(42, n => -n))

function fifth(a) { // 第五个
  return pipeline(a,
    _.rest,
    _.rest,
    _.rest,
    _.rest,
    _.first,
    )
}
console.log(fifth([1,2,3,4,5])) // 5

function negativeFifth(a) { // 负的第五
  return pipeline(a,
    fifth,
    n => -n)
}
console.log( negativeFifth([1,2,3,4,5,6])) // -5


function firstEditions(table) {
  return pipeline(table, 
      t => Utils.as(t, {ed: 'edition'}),
      t => Utils.project(t, ['title', 'edition']),
      t => Utils.restrict(t, book => book.edition === 1)
    )
}

let library = [
  {
    title: '数据结构',
    ed:1,
    author: '蔚敏老师'
  },
  {
    title: '算法',
    ed:2,
    author: '左大'
  },
  {
    title: '算法',
    ed:3,
    author: '阿北'
  },
  {
    title: 'es6',
    ed:3,
    author: '阮一峰'
  }
]

let ret = firstEditions(library)
console.log(ret)

// 关系运算符
let RQL = {
  select: Utils.curry2(Utils.project),
  as: Utils.curry2(Utils.as),
  where: Utils.curry2(Utils.restrict),
}

const firstEditionsRQL = function(table) {
  return pipeline(table
    ,RQL.as({ed: 'edition'})
    ,RQL.select(['title', 'edition'])
    ,RQL.where(book => book.edition === 1)
  )
}

console.log(firstEditionsRQL(library))

管道:使数据流更加明确,适合执行没有副作用的操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值