我想编写一个函数,其规范在下面的代码段中描述,这是我当前的实现。它确实有效。然而,我一直试图将它写成无点并完全作为ramda函数的组合而无法找到解决方案。这个问题与obj => map(key => recordSpec[key](obj[key])
有关,我无法通过这种方式减少这一点,我可以将整个事情写成无点的。
我该怎么办?
/**
* check that an object :
* - does not have any extra properties than the expected ones (strictness)
* - that its properties follow the defined specs
* Note that if a property is optional, the spec must include that case
* @param {Object.<String, Predicate>} recordSpec
* @returns {Predicate}
* @throws when recordSpec is not an object
*/
function isStrictRecordOf(recordSpec) {
return allPass([
// 1. no extra properties, i.e. all properties in obj are in recordSpec
// return true if recordSpec.keys - obj.keys is empty
pipe(keys, flip(difference)(keys(recordSpec)), isEmpty),
// 2. the properties in recordSpec all pass their corresponding predicate
// For each key, execute the corresponding predicate in recordSpec on the
// corresponding value in obj
pipe(obj => map(key => recordSpec[key](obj[key]), keys(recordSpec)), all(identity)),
]
)
}
例如,
isStrictRecordOf({a : isNumber, b : isString})({a:1, b:'2'}) -> true
isStrictRecordOf({a : isNumber, b : isString})({a:1, b:'2', c:3}) -> false
isStrictRecordOf({a : isNumber, b : isString})({a:1, b:2}) -> false
答案 0 :(得分:2)
实现这一目标的一种方法是使用R.where
,它使用像recordSpec
这样的规范对象,并使用第二个对象的相应键中的值应用每个谓词。
您的功能将如下所示:
const isStrictRecordOf = recordSpec => allPass([
pipe(keys, flip(difference)(keys(recordSpec)), isEmpty),
where(recordSpec)
])