函数柯里化(currying)

版权声明:本文为个人知识整理,欢迎指正、交流、转载。 https://blog.csdn.net/u014711094/article/details/82912836
  • 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/

猜你喜欢

转载自blog.csdn.net/u014711094/article/details/82912836