concept failure in category javascript

appears as: Failure, failure, failures, A failure
The Joy of JavaScript

This is an excerpt from Manning's book The Joy of JavaScript.

Remember earlier I mentioned that map and flatMap were universal and apply to much more than arrays? Just like Array#map, you can use Validation#map as a window to apply sequential operations over a single value. The main difference is that aside from mapping a function to a value, Validation#map also keeps track of its state: Success or Failure. Because the ADT always knows the context in which the mapped function is being applied, it frees you from having to add conditional validations blocks manually into every function. Here’s how countBlocksInFile looks with validation checks applied at every step of the way:

  • You lost the context in which the validation took place, which means you can’t apply specific rules nor exit with a proper validation message in the event of a failure
  • Listing 5.6 Success and Failure
    class Success extends Validation {
      static of(a) {
        return new Success(a)
      }
     
      get isSuccess() {
        return true  //#A
      }
    }
     
     
    class Failure extends Validation {
      get isFailure() {  //#A
        return true
      }
     
      static of(b) {
        return new Failure(b)
      }
     
      get() {  //#B
        throw new Error(`Can't extract the value of a Failure`)
      }
     
      getOrElse(defaultVal) { //#C
        return defaultVal
      }
    }
    Functional Programming in JavaScript

    This is an excerpt from Manning's book Functional Programming in JavaScript.

    A common use of Either is to hold the results of a computation that may fail to provide additional information as to what the failure is. In unrecoverable cases, the left can contain the proper exception object to throw. The following listing shows the implementation of the Either monad.

    Figure 5.9. An Either structure can store an object (on the right) or an Error (on the left) with proper stack trace information. This is useful to provide a single return value that can also contain an error message in case of failure.