简体   繁体   中英

How can i rewrite type checks of object props in Ramda

I'm trying put my head around how rewrite the following TS code using Ramda:

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));

I ended up with something like this, but it does not really work:

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)

Potentially, pickBy can be used to filter out props... but Im lost. Please help to connect the dots.

To transform an object properties by key and value, it's often easiest to convert the object to an array of [key, value] pairs via R.toPairs , transform the pairs (using R.filter in this case), and then convert back to an object using R.fromPairs .

To filter the pairs, I'm using R.where to check the key (index 0 in the pair), and the value (index 1 in the pair) by wrapping the RegExp, and the array of permitted types in functions.

Note: R.type returns the types in pascal case - String , Number , and 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM