1. 程式人生 > >函式柯里化(currying)

函式柯里化(currying)

  • currying的好處
Little pieces can be configured and reused with ease, without clutter.

Functions are used throughout.
  • 例子1
let add = (a, b, c) => a + b + c

let curryAdd = R.curry(add)

// 函式柯里化後,可按如下方式呼叫
curryAdd(1)(2)(3)			// 6
curryAdd(1, 2)(3)			// 6
curryAdd(1)(2, 3)			// 6

// 模擬,不是準確實現
let curryAdd = function (a) { return function (b) { return function (c) { return a + b + c } } }
  • 例子2
let objs = [{ id: 1 }, { id: 2 }, { id: 3 }]

let getProp = R.curry((p, o) => o[p])
let map = R.curry((fn, objs) => objs.map(fn))

let getIds = map(getProp('id'))
getIds(objs) // [1, 2, 3] -- 正常寫法 objs.map(o => o.id) // [1, 2, 3]
  • 例子3
// 見參考文章
let data = {
  result: "SUCCESS",
  interfaceVersion: "1.0.3",
  tasks: [
      {id: 104, complete: false,            priority: "high",
                dueDate: "2013-11-29",      username: "Scott",
                title:
"Do something", created: "9/22/2013"}, {id: 105, complete: false, priority: "medium", dueDate: "2013-11-22", username: "Lena", title: "Do something else", created: "9/22/2013"}, {id: 107, complete: true, priority: "high", dueDate: "2013-11-22", username: "Mike", title: "Fix the foo", created: "9/22/2013"}, {id: 110, complete: false, priority: "medium", dueDate: "2013-11-15", username: "Scott", title: "Rename everything", created: "10/2/2013"} ] } // 原文采用ramda function getIncompleteTaskSummaries(username) { Promise.resolve(data) .then(R.prop('tasks')) .then(R.filter(R.propEq('username', username))) .then(R.filter(R.propEq('complete', false))) .then(R.map(R.pick(['id', 'priority', 'dueDate', 'title']))) .then(R.sortBy(R.prop('dueDate'))) .then(console.log) } // 採用ES6格式 function getIncompleteTaskSummaries(username) { Promise.resolve(data) .then(data => { return data.tasks .filter(o => o.username === username && !o.complete) .map(({id, priority, dueDate, title}) => ({id, priority, dueDate, title})) .sort((o1, o2) => o1.dueDate > o2.dueDate) }) .then(console.log) }

參考:
https://ramdajs.com/
http://ramda.cn/