Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities.

This article also participated in the “Digitalstar Project” to win a creative gift package and creative incentive money

preface

After the book, we will optimize the maybe functor above. Previous chapter portal: juejin.cn/post/701840…

What is theEitherfunctor

  • EitherEither of the two, similar toif... else...The processing of
  • Exceptions make the function impure,EitherFunctors can be used to do exception handling

Start processing

1. Requirements identification

The maybe functor can’t determine the location of null. Not only does it handle null where it occurs, it can also be used to get information about where and where the exception occurs. Ok, it’s time to start implementing Either functor because it’s one of two, so we’ll create two types left and right

```js class left { ... } class right { ... } ` ` `Copy the code

2. The type of writing

In both of these classes, we write the method body, and they both require a static method, a map method, simple functors, recall: simple functor writing

```js class Left { static of (value) { return new Left(value) } constructor (value) { this._value = value } map (fn) { return this } } class Right { static of (value) { return new Right(value) } constructor (value) { this._value = value } Map (fn) {return right.of (fn(this._value))}} ' 'map (fn) {return right.of (fn(this._value))}}'Copy the code

3. The difference between functors

Let’s implement two functors using the two classes we implemented above. Let’s see what the difference is between them

```js
let r1 = Right.of(12).map(x => x + 2)
let r2 = Left.of(12).map(x => x + 2)
console.log(r1)
console.log(r2)
```
Copy the code

We can see thatRightThe value is12 + 2 = 14Correct output, howeverLeftIt returns the original argument, mainly becauseLeftIn themapIt’s straight backthis

Left returns the original functor directly to catch exceptions, and Right executes the input fn and returns a functor if there are no exceptions. Why would ** do that? **Copy the code

4. Why are two functors needed

For example, passing in an error JSON object is different from passing in a normal JSON object.  ```js function parseJSON (str) { try { return Right.of(JSON.parse(str)) } catch (e) { return Left.of({ error: Let r = parseJSON('{name: parseJSON ')}} zs}') console.log(r) let r1 = parseJSON(JSON.stringify({ name:'zs'} )) console.log(r) ``` ! [image.png](https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/472abe33d8004bb9998ddfd576a1fc5f~tplv-k3u1fbpfcp-watermark .image?)Copy the code

5. Summary

So now that we’ve shown you the Either functor, we can use that functor to handle exceptions and store error messages. Either functor is essentially a combination of two functors, one functor to do the correct logic and one functor to catch error messages

The complete code

class Left {
  static of (value) {
    return new Left(value)
  }
  constructor (value) {
    this._value = value
  }
  map (fn) {
    return this}}class Right {
   static of (value) {
    return new Right(value)
  }
  constructor (value) {
    this._value = value
  }
  map (fn) {
    return Right.of(fn(this._value))
  }
}
// Define a function
function parseJSON (str) {
  try {
      return Right.of(JSON.parse(str))
  } catch (e) {
      // Used to store error information
      return Left.of({ error: e.message})
  }
}
// Incorrect data was passed in
let r = parseJSON('{ name: zs}')
console.log(r)
// Pass in the correct data
let r1 = parseJSON(JSON.stringify({ name:'zs'}))console.log(r1)
let r3 = Right.of(12).map(x= > x + 2)
console.log(r3)
let r4 = Left.of(12).map(x= > x + 2)
console.log(r4)
Copy the code

conclusion

In this article, we have learned about the Either functor and its composition. After that, we are going to dive into the IO functor. See you in the next chapter!

Give a thumbs-up to those who come here!