【问题标题】:How can i rewrite type checks of object props in Ramda如何在 Ramda 中重写对象道具的类型检查
【发布时间】:2020-12-01 01:05:51
【问题描述】:

我正在尝试如何使用 Ramda 重写以下 TS 代码:

const uniqueIdentifierRegEx = /.*id.*|.*name.*|.*key.*/i;
const uniqueIdentifierPropTypes = ['string', 'number', 'bigint'];

const findUniqueProp = (obj: any) => Object.keys(obj)
    .filter(prop => uniqueIdentifierPropTypes.includes(typeof obj[prop]))
    .find(prop => uniqueIdentifierRegEx.test(prop));

我最终得到了这样的东西,但它并没有真正起作用:

const data = {a:1, name: 'name', nameFn: () => {}};
const uniqueIdentifierRegEx = /.*id.*|.*name.*|.*key.*/i;
const uniqueIdentifierPropTypes = ['string', 'number', 'bigint'];

const filterPred = curry((obj, prop_, types) => includes(type(prop(prop_, obj)), types));
const findProd = curry((prop_, regEx) => regEx.test(prop))

const findUniqueProp = (obj, types, regEx) =>
   pipe(
     keys,
     filter(filterPred(types)),
     find(findProd(regEx))
   )(obj)

findUniqueProp(data, uniqueIdentifierPropTypes, uniqueIdentifierRegEx)

可能,pickBy 可用于过滤掉道具……但我迷路了。请帮助连接点。

【问题讨论】:

    标签: javascript typescript functional-programming ramda.js


    【解决方案1】:

    要通过键和值转换对象属性,通常最简单的方法是通过R.toPairs 将对象转换为[key, value] 对的数组,转换对(在本例中使用R.filter),然后再转换回来使用R.fromPairs 到一个对象。

    为了过滤对,我使用R.where 来检查键(对中的索引 0)和值(对中的索引 1),方法是包装 RegExp,以及函数中允许的类型数组.

    注意:R.type 返回帕斯卡大小写的类型 - String、Number 和 BigInt。

    const { test, pipe, type, flip, includes, toPairs, filter, where, fromPairs } = R
    
    const uniqueIdentifierRegEx = test(/.*id.*|.*name.*|.*key.*/i) // test if string matches regexp
    const uniqueIdentifierPropTypes = pipe(type, flip(includes)(['String', 'Number', 'BigInt'])) // test if the type of the value is in the array
    
    const fn = pipe(
      toPairs, // convert to [key, value] pairs
      filter(where([ // filter and use where to check the key (0) and the value (1)
        uniqueIdentifierRegEx,
        uniqueIdentifierPropTypes
      ])),
      fromPairs // convert back to object
    )
    
    const data = {a: 1, name: 'name', nameFn: () => {}}
    
    const result = fn(data)
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.js"></script>

    【讨论】:

    • 谢谢你,伙计!看起来棒极了,不过 ramda 的可读性不太好。我不可能自己弄清楚。
    • 不客气 :) 查看 R.where 的更新(更改为数组)。
    • 我明白了,是的,好多了!
    猜你喜欢
    • 1970-01-01
    • 2020-04-27
    • 2011-01-27
    • 2011-01-25
    • 2010-11-24
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    相关资源
    最近更新 更多