Ramda 之 addIndex()

栏目: 编程语言 · 发布时间: 7年前

内容简介:若想在VS Code 1.33.1Quokka 1.0.209

若想在 Array.prototype.map() 的 Callback 得知目前 Element 的 Index,其 Callback 的第二個參數就是 Index,但 Ramda 的 map() 並沒有提供如此功能,該如何解決呢 ?

Version

VS Code 1.33.1

Quokka 1.0.209

Ramda 0.26.1

Array.prototype.map()

let data = [
  { title: 'FP in JavaScript', price: 100 },
  { title: 'RxJS in Action', price: 200 },
  { title: 'Speaking JavaScript', price: 300 }
];

let getBooks = arr => arr.map((x, i) => `${i}.${x.title}`);

console.dir(getBooks(data));

第 7 行

let getBooks = arr => arr.map((x, i) => `${i}.${x.title}`);

第二個參數 i 就是 index,可直接使用。

Ramda 之 addIndex()

addIndex()

import { map, addIndex } from 'ramda';
let data = [
  { title: 'FP in JavaScript', price: 100 },
  { title: 'RxJS in Action', price: 200 },
  { title: 'Speaking JavaScript', price: 300 }
];

let mapIndex = addIndex(map);
let getBooks = mapIndex((x, i) => `${i}.${x.title}`);

console.dir(getBooks(data));

第 8 行

let mapIndex = addIndex(map);

map() 必須經過 addIndex() 的包裝後,其 callback 才有 index 可用。

addIndex()

((a … → b) … → [a] → *) → ((a …, Int, [a] → b) … → [a] → *)

將 callback 加上 index

Ramda 之 addIndex()

Point-free

import { map, addIndex, useWith, concat, identity, prop, flip, pipe } from 'ramda';

let data = [
  { title: 'FP in JavaScript', price: 100 },
  { title: 'RxJS in Action', price: 200 },
  { title: 'Speaking JavaScript', price: 300 }
];

let mapIndex = addIndex(map);
let title = pipe(prop('title'), concat('.'));
let index = pipe(identity, String);
let getBooks = mapIndex(useWith(
  flip(concat), [title, index])
);

console.dir(getBooks(data));

也可以將 callback 部分進一步 point-free。

這個 point-free 在 production code 就不建議使用,因為太複雜了,可讀性不高,僅適合拿來練習 point-free

Ramda 之 addIndex()

Conclusion

addIndex()

Reference

Ramda , map()

Ramda , addIndex()


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

查看所有标签

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

鼠标宣言

鼠标宣言

约翰·里德尔 / 倪萍、梅清豪 / 上海人民 / 2005-08-01 / 25.00

本书针对信息时代营销者不知该如何满足消费者的营销困境,提出了崭新的解决方案——以新技术为基础的群体筛选和推荐系统。随着信息管理软件和internet的高速发展,群体筛选技术下的推荐系统通过大量有关消费者偏好和购物记录的信息,以及对产品特征的准确把握,能够为消费者进行精确的推荐,提高了消费者的购物效率和准确度以及营销者的营销效率和竞争力。本书通过通俗而到位的讲解,向读者全面介绍了有关群体筛选技术的理......一起来看看 《鼠标宣言》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

SHA 加密
SHA 加密

SHA 加密工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试