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 ,我們想做以下加工:

  1. title 字串前後可能有 space,需使用 trim() 加以過濾
  2. year 的數字全部加 1
  3. 其餘 property 全部保留

標準做法是使用 map() 搭配 callback function,但這有幾個缺點:

  1. 若 object 的 property 很多,而要改變的 property 很少,沒有改變的 property 也要照抄一次
  2. Callback function 並非 Point-free

Ramda 之 evolve()

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。

Ramda 之 evolve()

Conclusion

  • 使用 evolve() 可使 Point-free 過後的 callback 語意更清楚,而且 spec object 只要描述要改變的 property 即可

Reference

Ramda , map()

Ramda , evolve()

Ramda , trim()

Ramda , add()


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

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

Computers and Intractability

Computers and Intractability

M R Garey、D S Johnson / W. H. Freeman / 1979-4-26 / GBP 53.99

This book's introduction features a humorous story of a man with a line of people behind him, who explains to his boss, "I can't find an efficient algorithm, but neither can all these famous people." ......一起来看看 《Computers and Intractability》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

SHA 加密
SHA 加密

SHA 加密工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具