内容简介:同一個需求在 Ramda 常有不同的寫法,取決於你對 Operator 熟悉程度與經驗,隨著 Ramda 功力的提升,就能寫出更精簡的程式碼。Ramda 0.26.1一個實務上常見的需求,由 API 所得到的資料只有
同一個需求在 Ramda 常有不同的寫法,取決於你對 Operator 熟悉程度與經驗,隨著 Ramda 功力的提升,就能寫出更精簡的程式碼。
Version
Ramda 0.26.1
Imperative
const data = [1, 2, 3];
const bookLut = {
1: 'Functional Programming in JavaScript',
2: 'RxJS in Action',
3: 'Speaking JavaScript',
};
const getBooks = data => {
let result = [];
for(let item of data) {
result.push(bookLut[item]);
}
return result;
};
const result = getBooks(data);
console.log(result);
一個實務上常見的需求,由 API 所得到的資料只有 代碼 ,而我們需要根據 代碼 轉成 對應資料 顯示。
至於 代碼 與 顯示文字 的對照表,會存在 object 內。
Imperative 會使用 for loop,若在 object 比對到,則 push() 到新的 result array,最後回傳 result array。
Array.prototype
const data = [1, 2, 3];
const bookLut = {
1: 'Functional Programming in JavaScript',
2: 'RxJS in Action',
3: 'Speaking JavaScript',
};
const getBooks = data => data.map(x => bookLut[x]);
const result = getBooks(data);
console.log(result);
Array.prototype 有自帶 map() ,所以我們也可以直接使用,再透過 bookLut[x] 加以對照轉換。
這種寫法已經比 Imperative 精簡很多,但仍有兩個問題:
- 由於內建的
map()不是 Curried Function,因此getBooks()仍然要提供data參數,無法如 Point-Free Style 那樣精簡 -
x => bookLut[x]這種 callback,是否有 Point-free 寫法呢 ?
Ramda
import { map } from 'ramda';
const data = [1, 2, 3];
const bookLut = {
1: 'Functional Programming in JavaScript',
2: 'RxJS in Action',
3: 'Speaking JavaScript',
};
const getBooks = map(x => bookLut[x]);
const result = getBooks(data);
console.log(result);
Ramda 亦提供 map() operator,與 Array.prototype 的 map() 不同在於:他是個 Curried Function,最後一個參數為 data ,因此 getBooks() 可以使用 Point-free 寫法,如此將省下一個參數,程式碼更精簡。
map()
(a -> b) -> a -> b
將 a 格式資料轉換成 b 格式資料,且筆數不變
第一個參數 (a -> b) 為 function,也就是 map() 要轉換的 function。
第二個參數 a 為 data ,也由於最後一個參數為 data ,使得 map() 可使用 Point-free。
回傳 b ,也就是新的 data 。
import { map, prop, __ } from 'ramda';
const data = [1, 2, 3];
const bookLut = {
1: 'Functional Programming in JavaScript',
2: 'RxJS in Action',
3: 'Speaking JavaScript',
};
const getBooks = map(prop(__, bookLut));
const result = getBooks(data);
console.log(result);
不過之前的寫法, map() 的 callback 仍然不是 Point-free,Ramda 特別提供了 prop() operator,專門產生這類 callback。
Ramda 的 operator 最後一個參數都是 data,因此可以很簡單的省略 data 參數做 Point-free,但本文需求有些特別, map() 傳進來的資料並不是 prop() 最後一個參數,而是第一個參數。
對於這種特殊需求,Ramda 另外提供 __ operator 做 placeholder,專門負責傳入 data。
prop()
s -> {s: a} -> a | undefine
傳入 property key,傳回 object -> a 的 callback
第一個參數 s 為 object 的 property key。
回傳 {s: a} -> a | undefine callback function。
__
針對 data 不在最後一個參數的 operator 做 placeholder
Conclusion
prop() __
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Open Data Structures
Pat Morin / AU Press / 2013-6 / USD 29.66
Offered as an introduction to the field of data structures and algorithms, Open Data Structures covers the implementation and analysis of data structures for sequences (lists), queues, priority queues......一起来看看 《Open Data Structures》 这本书的介绍吧!