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))
管道:使数据流更加明确,适合执行没有副作用的操作。