過程式編碼是這樣的:函數
var getAdminUsers = users => { var emails = [] users.forEach(v=>{ v.role==='admin' && emails.push(v.email) }) return emails }
易讀的方式重寫:ui
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函數:spa
const pipe = (...args) => x=> args.reduce((ini, fn)=> fn(ini), x)
下面開始放大招:code
var getAdminEmails = pipe( filter( propEq('admin')('role')), map( prop('email')));
之後就能夠這樣愉快地調用了:blog
var arr = [{role: 'admin', email: 'suibdkhgigh'}] getAdminEmails(arr) //["suibdkhgigh"]