我如何在Ramda中重写对象道具的类型检查

问题描述

我正在尝试着用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','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可以用来过滤道具……但是我迷路了。请帮助连接点。

解决方法

要通过键和值转换对象属性,通常最容易通过[key,value]将对象转换为R.toPairs对数组,然后转换对(在这种情况下使用R.filter ),然后使用R.fromPairs转换回对象。

要过滤对,我使用R.where通过包装RegExp和允许的类型数组来检查键(对中的索引0)和值(对中的索引1)。在功能上。

注意:R.type以pascal大小写返回类型-StringNumberBigInt

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>

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...