问题描述
我正在尝试着用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大小写返回类型-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>