简体   繁体   English

与Ramda一起检查帮助器

[英]type checking helper with Ramda

I want to write a function whose specifications is described in the piece of code below which is the current implementation I have. 我想编写一个函数,其规范在下面的代码段中描述,这是我当前的实现。 It does work. 它确实有效。 However I have been trying for a while to write it pointfree and entirely as a composition of ramda functions and could not find a solution. 然而,我一直试图将它写成无点并完全作为ramda函数的组合而无法找到解决方案。 The issue is linked to obj => map(key => recordSpec[key](obj[key]) which I cannot reduce in a way that I can write the whole thing pointfree. 这个问题与obj => map(key => recordSpec[key](obj[key]) ,我无法以一种可以编写整个事物的方式减少。

How could I do? 我该怎么办?

/** * 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, ie 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)), ] ) }

For instance, 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 例如, 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

One way to achieve this would be to use R.where , which takes a spec object like your recordSpec and applies each predicate with the value from the corresponding keys of the second object. 实现此目的的一种方法是使用R.where ,它接受像recordSpec这样的spec对象,并使用第二个对象的相应键中的值应用每个谓词。

Your function would then look like: 您的功能将如下所示:

const isStrictRecordOf = recordSpec => allPass([
  pipe(keys, flip(difference)(keys(recordSpec)), isEmpty),
  where(recordSpec)
])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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