liveBook · Manning

HasValidation

As explained in The Joy of JavaScript

A book-local mixin that adds validation behavior to objects by contributing a validation API.

HasValidation is a composable JavaScript mixin that adds a validate method to objects. It combines each object’s own isValid check with validation of its nested elements. section 5.5.7

The mixin relies on a small interface and a recursive validation model:

  • Each participating object supplies isValid(), returning a Validation result containing either Success or Failure. section 5.5.7 section 5.5.3
  • Each traversable object exposes its children through iteration, allowing validate to descend from a blockchain to blocks and transactions. section 5.5.7 section 7.5.5
  • Validation results compose with flatMap, so failures propagate and later checks can be skipped. section 5.5.3

Validating a blockchain tree

Assign HasValidation to Blockchain, Block, and Transaction prototypes. Calling chain.validate() checks the chain itself, every block, and every transaction through one shared API. A streaming variant can call block.validate() as blocks are hydrated from a file, counting two valid non-genesis blocks. section 5.5.7 section 9.2.3

Listing 5.23 HasValidation mixin
const HasValidation = () => ({
    validate() {   
       return [...this]                                             #1
        .reduce((validationResult, nextItem) =>                     #2
             validationResult.flatMap(() => nextItem.validate()),
          this.isValid()                                            #3
         );
    }
});

The core implementation shows validate enumerating this object, reducing child results, and starting with this.isValid(). section 5.5.7

How The Joy of JavaScript covers it

How deep it goes
Defines recursive traversal, isValid, reduce, and Validation results, then defers array-free early termination to iterator-based refinement.
Examples
Uses Blockchain, Block, and Transaction objects, tampered block hashes, iterable children, and asynchronous block streams.
What it assumes
Assumes JavaScript object composition and recursion, while introducing Validation outcomes and Symbol.iterator as required mechanisms.
What you can do after
Apply it via Object.assign, implement isValid and iteration, and validate nested models or streamed blocks with shared logic.
How it connects
Connects mixins, object composition, Validation, recursion, blockchain models, and Symbol.iterator to composable tree validation.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Joy of JavaScript. The section links point to the parts of the book it draws on.