Ramda的类型检查助手

use*_*222 5 javascript ramda.js

我想编写一个函数,其规范在下面的代码段中描述,这是我目前的实现。确实有效。但是,我已经尝试了一段时间,将其写为毫无意义,并且完全是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

Sco*_*her 2

实现此目的的一种方法是使用R.where,它采用像您这样的规范对象recordSpec,并将每个谓词与第二个对象的相应键中的值应用。

你的函数将如下所示:

const isStrictRecordOf = recordSpec => allPass([
  pipe(keys, flip(difference)(keys(recordSpec)), isEmpty),
  where(recordSpec)
])
Run Code Online (Sandbox Code Playgroud)