我想编写一个函数,其规范在下面的代码段中进行了描述,这是我目前的实现。它确实起作用。但是,我一直在尝试将其写为无点,并且完全以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'}) -> trueisStrictRecordOf({a : isNumber, b : isString})({a:1, b:'2', c:3}) -> falseisStrictRecordOf({a : isNumber, b : isString})({a:1, b:2}) -> false
最佳答案
实现此目的的一种方法是使用 R.where
,它接受一个像您的recordSpec
这样的spec对象,并将每个谓词与第二个对象的相应键中的值一起应用。
您的函数将如下所示:
const isStrictRecordOf = recordSpec => allPass([
pipe(keys, flip(difference)(keys(recordSpec)), isEmpty),
where(recordSpec)
])
关于javascript - Ramda的类型检查助手,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41420899/