Ramda 之 evolve()
栏目: JavaScript · 发布时间: 6年前
内容简介:實務上在使用VS Code 1.31.1Quokka 1.0.136
實務上在使用 map() 時,經常是 Object 的 Key 不變,但 Value 稍作加工,此時當然可以使用 Callback Function,但也可使用 Ramda 的 evlove() 使 Callback Function 也 Point-free。
Version
VS Code 1.31.1
Quokka 1.0.136
Ramda 0.26.1
Non Point-free
import { map } from 'ramda'
const data = [
{ id: 1, title: 'Impatient JavaScript ', year: 2018 },
{ id: 2, title: ' RxJS in Action', year: 2017 },
{ id: 3, title: ' Speaking JavaScript ', year: 2014 },
]
const getBooks = map(x => ({
id: x.id,
title: x.title.trim(),
year: x.year + 1,
}))
console.dir(getBooks(data))
對於原本的 data ,我們想做以下加工:
-
title字串前後可能有 space,需使用trim()加以過濾 -
year的數字全部加1 - 其餘 property 全部保留
標準做法是使用 map() 搭配 callback function,但這有幾個缺點:
- 若 object 的 property 很多,而要改變的 property 很少,沒有改變的 property 也要照抄一次
- Callback function 並非 Point-free
Point-free
import { evolve, map, trim, add } from 'ramda'
const data = [
{ id: 1, title: 'Impatient JavaScript ', year: 2018 },
{ id: 2, title: ' RxJS in Action', year: 2017 },
{ id: 3, title: ' Speaking JavaScript ', year: 2014 },
]
const getBooks = map(evolve({
'title': trim,
'year': add(1),
}))
console.dir(getBooks(data))
evolve()
Object 在 key 不變的前提下,將 value 透過 transformation function 加以改變
{k: (v → v)} → {k: v} → {k: v}
{k: (v → v)} :Spec object,描述 object 該如何轉換,只要加上要改變的 key,與其對應的 transformation function 即可
{k: v} :要改變的 source object
{k: v} :改變結果的 target object
trim() 與 add() 也一併使用 Ramda 所提供的 operator。
Conclusion
- 使用
evolve()可使 Point-free 過後的 callback 語意更清楚,而且 spec object 只要描述要改變的 property 即可
Reference
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Remote
Jason Fried、David Heinemeier Hansson / Crown Business / 2013-10-29 / CAD 26.95
The “work from home” phenomenon is thoroughly explored in this illuminating new book from bestselling 37signals founders Fried and Hansson, who point to the surging trend of employees working from hom......一起来看看 《Remote》 这本书的介绍吧!