検証には検証ツールが必要です。楽しみのためにそれを忘れましょう。バリデーターを使用して、ネストされたデータ構造を見ていきましょう。クレイジー、あなたは言う!

どこで走りますか?
電話帳を調べてみましょう。
const phoneBook = {
andrew: ["+345356245254", "+313232312312"],
vasilina: ["+132313123123"],
serhiy: ["+587234878234", "+321323124123"],
};
何を手に入れたいですか?
すべての番号のリストを取得しましょう。
どうすればいいですか?
これは4つのステップで行います。
- データ検証のためにライブラリを接続しましょう
- 定期的な検証関数を作成しましょう
- 数値を収集する副作用を配列に追加する
- 関数でラップしましょう
検証ライブラリを使用しますquartet
:
import { v } from "quartet";
検証関数を書いてみましょう:
const checkPhoneBook = v({
[v.rest]: v.arrayOf(v.string),
});
, :
checkPhoneBook({}); // true
checkPhoneBook({ andrew: ["123321"] }); // true
checkPhoneBook({ andrew: null }); // false
: .
const phoneNumbers = [];
const checkAndCollect = v({
[v.rest]: v.arrayOf(
v.and(
v.string,
v.custom((phoneNumber) => {
phoneNumbers.push(phoneNumber);
return true;
})
)
),
});
:
checkAndCollect({
andrew: ["+345356245254", "+313232312312"],
vasilina: ["+132313123123"],
serhiy: ["+587234878234", "+321323124123"],
});
true
. ! : phoneNumbers
.
console.log(phoneNumbers);
// [
// '+345356245254',
// '+313232312312',
// '+132313123123',
// '+587234878234',
// '+321323124123'
// ]
«»:
import { v } from "quartet";
/**
* @param {Record<string, string[]>} phoneBook
* @returns {string[]} phone numbers
*/
function collectPhoneNumbers(phoneBook) {
const phoneNumbers = [];
const checkAndCollect = v({
[v.rest]: v.arrayOf(
v.and(
v.string,
v.custom((phoneNumber) => {
phoneNumbers.push(phoneNumber);
return true;
})
)
),
});
checkAndCollect(phoneBook);
return phoneNumbers;
}
. production . :
- . — .
- . .
- . .
- このタスクにより適したコードがあります。
/**
* @param {Record<string, string[]>} phoneBook
* @returns {string[]} phone numbers
*/
function collectPhoneNumbers(phoneBook) {
const phoneNumbers = [];
const personNames = Object.keys(phoneBook);
for (const personName of personNames) {
const personPhoneNumbers = phoneBook[personName];
phoneNumbers.push(...personPhoneNumbers);
}
return phoneNumbers;
}
あとがき
これは私が日曜日の夜に思いついた一種の楽しみです。あなたの頭に浮かぶ奇妙なことは何ですか?コメントを書いてください。