Strange uses of validation

Validators are needed for validation. Let's forget about it for fun. Let's walk through the nested data structure using the validator. Crazy, you say!







image Nordic YES







Where will we run?



Let's run through the phone book:







const phoneBook = {
  andrew: ["+345356245254", "+313232312312"],
  vasilina: ["+132313123123"],
  serhiy: ["+587234878234", "+321323124123"],
};
      
      





What do we want to get?



Let's get a list of all numbers.







How do we do it?



We will do this in 4 steps:







  • Let's connect the library for data validation
  • Let's create a regular validation function
  • Add the side effect of collecting numbers into an array
  • Let's wrap in a function


We will use the validation library quartet



:







import { v } from "quartet";
      
      





Let's write a validation function:







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 . :







  • . โ€” .
  • . .
  • . .
  • There is a code more suitable for this task:


/**
 * @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;
}
      
      





Afterword



This is the kind of fun I came up with on Sunday evening. What's strange that comes to your mind? Write in the comments.








All Articles