1
我有一个场景,我需要从对象中抓取第一个字符串,但前提是匹配发生在已经预先定义的某个路径中。从一系列可能的路径中获取字符串
{ id: 'I60ODI', description: 'some random description' }
{ foo: 'bar', description: { color: 'green', text: 'some description within text' } }
当设置或者两个物体的上面,我期望溶液返回任一some random description
或some description within text
,前提是两个可能的路径是obj.description
和obj.description.text
。未来可能还需要添加新路径,因此添加它们需要很容易。
这是我迄今为止实施的解决方案,但对我来说这似乎并不理想。
// require the ramda library
const R = require('ramda');
// is the provided value a string?
const isString = R.ifElse(R.compose(R.equals('string'), (val) => typeof val), R.identity, R.always(false));
const addStringCheck = t => R.compose(isString, t);
// the possible paths to take (subject to scale)
const possiblePaths = [
R.path(['description']),
R.path(['description', 'text'])
];
// add the string check to each of the potential paths
const mappedPaths = R.map((x) => addStringCheck(x), possiblePaths);
// select the first occurrence of a string
const extractString = R.either(...mappedPaths);
// two test objects
const firstObject = { description: 'some random description' };
const secondObject = { description: { text: 'some description within text' } };
const thirdObject = { foo: 'bar' };
console.log(extractString(firstObject)); // 'some random description'
console.log(extractString(secondObject)); // 'some description within text'
console.log(extractString(thirdObject)); // false
如果经验丰富的功能程序员可能会为我提供一些替代方法来实现,我将非常感激。谢谢。
由于您有工作代码,并且真的要求审查,所以此问题更适合于[CodeReview](https://codereview.stackexchange.com/)。 – trincot
由于您的更新,我删除了我的答案。但我同意上面的评论。你有使用你想要使用的框架的工作代码。听起来像代码审查。 – user2263572
是的,我同意你们。感谢您的时间和意见。 [问题已被移动](https://codereview.stackexchange.com/q/177392/150458) – user2627546