Pointfree Javascript: Pointfree编程风格
过程式编码是这样的:
var getAdminUsers = users => { var emails = [] users.forEach(v=>{ v.role==='admin' && emails.push(v.email) }) return emails }
易读的方式重写:
let getAdminEmails = users => users .filter(u => u.role === 'admin') .map(u => u.email);
Pointfree :
var prop = p => x => x[p]; var map = f => list => list.map(f);
var propEq = v => p => obj => prop(p)(obj) === v; var filter = f => list => list.filter(f);
pipe函数:
const pipe = (...args) => x=> args.reduce((ini, fn)=> fn(ini), x)
下面开始放大招:
var getAdminEmails = pipe( filter( propEq('admin')('role')), map( prop('email')));
以后就可以这样愉快地调用了:
var arr = [{role: 'admin', email: 'suibdkhgigh'}] getAdminEmails(arr) //["suibdkhgigh"]