Ramda 之 useWith()

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

内容简介:對於只有一個參數的 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()》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

模式识别

模式识别

(希)Sergios Theodoridis、(希)Konstantinos Koutroumbas / 电子工业出版社 / 2010-2 / 75.00元

本书全面阐述了模式识别的基础理论、最新方法以及各种应用。模式识别是信息科学和人工智能的重要组成部分,主要应用领域有图像分析、光学字符识别、信道均衡、语言识别和音频分类等。本书在完美地结合当前的理论与实践的基础上,讨论了贝叶斯分类、贝叶斯网络、线性和非线性分类器设计、上下文相关分类、特征生成、特征选取技术、学习理论的基本概念以及聚类概念与算法。与前一版相比,增加了大数据集和高维数据相关的最新算法,这......一起来看看 《模式识别》 这本书的介绍吧!

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

在线 XML 格式化压缩工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具