Ramda 之 useWith()

栏目: JavaScript · 发布时间: 5年前

内容简介:對於只有一個參數的 function,我們可以很輕易地 Point-free,對於兩個以上參數的 function 呢 ? 這時就要使用 Ramda 殺手級 operator:WebStorm 2018.3.3Quokka 1.0.136

對於只有一個參數的 function,我們可以很輕易地 Point-free,對於兩個以上參數的 function 呢 ? 這時就要使用 Ramda 殺手級 operator: useWith()

Version

WebStorm 2018.3.3

Quokka 1.0.136

Ramda 0.26.1

Non Point-free

import { find, propEq } from 'ramda';

const data = [
  { id: 1, title: 'Functional Programming in JavaScript' },
  { id: 2, title: 'RxJS in Action' },
  { id: 3, title: 'Speaking JavaScript' },
];

const getBook = (id, data) => find(propEq('id', id), data);
console.dir(getBook(1, data));

若我們想根據 id 找資料,建立了 getBook() ,其中第一個參數為要搜尋的 id ,第二個參數為 data ,再使用 find() 找到該 object。

find()

(a -> boolean) -> [a] -> a | undefined

根據 predicate function 搜尋 array 中的資料

這樣寫是 OK 的,唯 getBook() 尚有兩個參數 iddata ,並不是 Point-free。

Ramda 之 useWith()

Point-free

import { find, propEq, useWith, identity } from 'ramda';

const data = [
  { id: 1, title: 'Functional Programming in JavaScript' },
  { id: 2, title: 'RxJS in Action' },
  { id: 3, title: 'Speaking JavaScript' },
];

/** a -> [a] -> a | undefined */
const getBook = useWith(find, [propEq('id'), identity]);
console.dir(getBook(1, data));

對於這種超過一個參數的 function,若我們想做 Point-free,我們可以使用 Ramda 的 useWith() ,他將回傳一個新的 curried function,且參數個數與原本 function 相同,最重要它是 Point-free。

useWith()

((x1, x2, ...) -> z) -> [(a -> x1), (b -> x2), ...] -> (a -> b -> ... -> z)

建立一個與原 function 參數個數相同的新 function,且各參數會先經過 transform function 處理過再傳給原 function 執行

((x1, x2, ...) -> z) :原本尚未 curried、尚未 Point-free 的 function

[(a -> x1), (b -> x2), ...] :為 array,有幾個參數就會有幾個 transformer function,新 function 的所有參數,都會經過 transformer function 執行過,結果才會傳給原 function

(a -> b -> ... -> z) :回傳新 function,且是 curried function

Ramda 之 useWith()

第 9 行

const getBook = (id, data) => find(propEq('id', id), data);
/** a -> [a] -> a | undefined */
const getBook = useWith(find, [propEq('id'), identity]);

要將 getBook() 重構成 Point-free 很簡單:

  1. find 放在 useWith() 的第一個參數
  2. 將原本 在 find() 第二個參數的 propEq('id') 改寫在 array 內
  3. id 不變,則使用 identity()

identity()

a -> a

建立傳回原本值的 function

如此 iddata 兩參數就被幹掉了,成了 Point-free。

useWith() 寫法雖然精簡,但 Point-free 版本日後可能一時看不出其 signature,建議馬上補上 signature 註解,其格式可模仿 Ramda 官網文件

Ramda 之 useWith()

Conclusion

useWith()
useWith()

Reference

Ramda , find()

Ramda , useWith()

Ramda , identity()


以上所述就是小编给大家介绍的《Ramda 之 useWith()》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

C++程序设计语言

C++程序设计语言

Bjarne Stroustrup / 裘宗燕 / 机械工业出版社 / 2010-3-1 / 99.00元

本书是在C++语言和程序设计领域具有深远影响、畅销不衰的著作,由C++语言的设计者编写,对C++语言进行了最全面、最权威的论述,覆盖标准C++以及由C++所支持的关键性编程技术和设计技术。本书英文原版一经面世,即引起业内人士的高度评价和热烈欢迎,先后被翻译成德、希、匈、西、荷、法、日、俄、中、韩等近20种语言,数以百万计的程序员从中获益,是无可取代的C++经典力作。 在本书英文原版面世10年......一起来看看 《C++程序设计语言》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

SHA 加密
SHA 加密

SHA 加密工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具