Ramda 之 pick()

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

内容简介:實務上最常使用的WebStorm 2018.3.3Quokka 1.0.134

實務上最常使用的 map() ,就是從 Object 眾多 Property 中,僅擷取部分 Property,Ramda 提供了 pick() 達成此功能。

Version

WebStorm 2018.3.3

Quokka 1.0.134

Ramda 0.26.1

Non Point-free

import { map } from 'ramda';

const data = [
  { id: 1, title: 'Functional Programming in JavaScript', year: 2016 },
  { id: 2, title: 'RxJS in Action', year: 2017 },
  { id: 3, title: 'Speaking JavaScript', year: 2014 },
];

const getBooks = map(x => ({ title: x.title, year: x.year }));
console.dir(getBooks(data));

若我們只要 titleyear 兩個 property,可直接使用 Arrow Function。

但因為 callback 還有 x 參數,所以並不是 Point-free。

Ramda 之 pick()

Point-free

import { map, pick } from 'ramda';

const data = [
  { id: 1, title: 'Functional Programming in JavaScript', year: 2016 },
  { id: 2, title: 'RxJS in Action', year: 2017 },
  { id: 3, title: 'Speaking JavaScript', year: 2014 },
];

const getBooks = map(pick(['title', 'year']));
console.dir(getBooks(data));

若想要 map() 的 callback 也 Point-free,可在搭配 pick() ,傳入 property 的 array 即可。

pick()

[k] -> {k: v} -> {k: v}

從一個 object 中抽取部分 property 成為新的 object

[k] :要抽取的 property

{k: v} :data 為 object

{k: v} : 回傳新的 object

Ramda 之 pick()

Conclusion

  • pick() 使得 map() 的 callback 更為精簡,這就是 Point-free 的魔力

Reference

Ramda , map()

Ramda , pick()


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

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

Sass and Compass in Action

Sass and Compass in Action

Wynn Netherland、Nathan Weizenbaum、Chris Eppstein、Brandon Mathis / Manning Publications / 2013-8-2 / USD 44.99

Written by Sass and Compass creators * Complete Sass language reference * Covers prominent Compass community plug-ins * Innovative approach to creating stylesheets Cascading Style Sheets paint the we......一起来看看 《Sass and Compass in Action》 这本书的介绍吧!

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具