簡體   English   中英

與Ramda一起檢查幫助器

[英]type checking helper with Ramda

我想編寫一個函數,其規范在下面的代碼段中描述,這是我當前的實現。 它確實有效。 然而,我一直試圖將它寫成無點並完全作為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, 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)), ] ) }

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

實現此目的的一種方法是使用R.where ,它接受像recordSpec這樣的spec對象,並使用第二個對象的相應鍵中的值應用每個謂詞。

您的功能將如下所示:

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