2017-10-07 68 views
1

我有一个场景,我需要从对象中抓取第一个字符串,但前提是匹配发生在已经预先定义的某个路径中。从一系列可能的路径中获取字符串

{ id: 'I60ODI', description: 'some random description' } 
{ foo: 'bar', description: { color: 'green', text: 'some description within text' } } 

当设置或者两个物体的上面,我期望溶液返回任一some random descriptionsome description within text,前提是两个可能的路径是obj.descriptionobj.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 

如果经验丰富的功能程序员可能会为我提供一些替代方法来实现,我将非常感激。谢谢。

+0

由于您有工作代码,并且真的要求审查,所以此问题更适合于[CodeReview](https://codereview.stackexchange.com/)。 – trincot

+0

由于您的更新,我删除了我的答案。但我同意上面的评论。你有使用你想要使用的框架的工作代码。听起来像代码审查。 – user2263572

+0

是的,我同意你们。感谢您的时间和意见。 [问题已被移动](https://codereview.stackexchange.com/q/177392/150458) – user2627546

回答

1

这工作,我认为这是清洁:

const extract = curry((defaultVal, paths, obj) => pipe( 
    find(pipe(path(__, obj), is(String))), 
    ifElse(is(Array), path(__, obj), always(defaultVal)) 
)(paths)) 

const paths = [['description'], ['description', 'text']] 

extract(false, paths, firstObject) //=> "some random description" 
extract(false, paths, secondObject) //=> "some description within text" 
extract(false, paths, thirdObject) //=> false 

我个人会发现在''更好的默认比false,但这是你的电话。

这可以避免映射到所有路径,当找到第一个路径时停止。它还使用Ramda的is来替换您的复杂isStringR.is(String)。而咖喱可以让你提供第一个或前两个参数来创建更有用的功能。

您可以在Ramda REPL中看到此操作。

相关问题