使用 Maybe 自行組合 safeNth()
栏目: JavaScript · 发布时间: 7年前
内容简介:Ramda 有些 Function 會回傳VS Code 1.33.1Quokka 1.0.209
Ramda 有些 Function 會回傳 undefined ,這些 Function 常常會忘記處理 undefined 而產生 Bug,比較好的方式是改回傳 Maybe ,可避免忘記處理 undefined 。
Version
VS Code 1.33.1
Quokka 1.0.209
Ramda 0.26.1
nth()
import { nth } from 'ramda';
let data = [
{ title: 'FP in JavaScript', price: 100 },
{ title: 'RxJS in Action', price: 200 },
{ title: 'Speaking JavaScript', price: 300 }
];
console.log(nth(1)(data).title);
console.log(nth(3)(data).title);
使用 Ramda 的 nth() ,取出資料後為 object,取其 title property 顯示。
nth()
Number -> [a] -> a | Undefined
回傳 array 的 nth element
Number : n th element
[a] :data 為 array
a | Undefined :若找得到則傳回 element,找不到則傳回 undefined
但別忘了 nth() 可能回傳 undefined ,因此很容易產生 Cannot read property of undefined 的 run-time 錯誤。
當然可以搭配 Ramda 的 propOr() 避免,但只要你稍微不小心,還是會忘了使用 propOr()
safeNth()
import { nth } from 'ramda';
import { isObject, safe } from 'crocks';
let data = [
{ title: 'FP in JavaScript', price: 100 },
{ title: 'RxJS in Action', price: 200 },
{ title: 'Speaking JavaScript', price: 300 }
];
// safeNth :: Number -> [a] -> Maybe a
let safeNth = ofst => arr => safe(isObject)(nth(ofst, arr));
console.log(safeNth(1)(data).option({ title: 'No title' }).title);
console.log(safeNth(3)(data).option({ title: 'No title' }).title);
第 2 行
import { isObject, safe } from 'crocks';
使用 Crocks 的 isObject() 與 safe() 。
第 10 行
// safeNth :: Number -> [a] -> Maybe a let safeNth = ofst => arr => safe(isObject)(nth(ofst, arr));
自行建立 saveNth() ,signature 與 Ramda 的 nth() 完全相同,差異只在於回傳 Maybe ,而不是 a | Undefiend 。
safeNth()
Number -> [a] -> Maybe a
回傳 array 的 nth element
Number : n th element
[a] :data 為 array
Maybe a :無論找不找得到都回傳 Maybe
safe(isObject)
由 Crocks 的 safe() 與 isObject() 組合出 function,若 nth() 結果為 object,則以 Just 包進 Maybe ,否則以 Nothing 包進 Maybe ,最後 safeNth() 回傳 Maybe 。
13 行
console.log(safeNth(1)(data).option({ title: 'No title' }).title);
因為 safeNth() 回傳為 Maybe ,所以取出資料時一定要透過 option() 才能取回 object,因此必須提供 default value 處理 Nothing 。
Maybe 強迫你要使用 option() 才能取回 object,因此你不可能忘記處理 Nothing ;不像 undefined 並沒有強迫處理,這就是常見的 bug 來源
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Build Your Own Web Site the Right Way Using HTML & CSS
Ian Lloyd / SitePoint / 2006-05-02 / USD 29.95
Build Your Own Website The Right Way Using HTML & CSS teaches web development from scratch, without assuming any previous knowledge of HTML, CSS or web development techniques. This book introduces you......一起来看看 《Build Your Own Web Site the Right Way Using HTML & CSS》 这本书的介绍吧!