Monads-Either.examples.js

https://github.com/eu81273/jsfiddle-console

by dimitrs_papadimitriou

HTML

<script src="https://rawgit.com/eu81273/jsfiddle-console/master/console.js"></script>

JavaScript

var some = (v) => ({
    map: (f) => some(f(v)),
    toEither: (defaultLeft) => right(v),
    cata: alg => alg.Ok(v)
  });

  var none = () => ({
    map: (f) => none(),
    toEither: (defaultLeft) => left(defaultLeft),
    cata: alg => alg.Error()
  });


  const right = (v) => ({
    map: (f) => right(f(v)),
    bind: f => f(v),
    cata: (alg) => alg.right(v),
  });

  const left = (v) => ({
    map: (_) => left(v),
    bind: f => left(v),
    cata: (alg) => alg.left(v),
  });

  Array.prototype.safeHead = function () {
    return this.length > 0 ?
      some(this[0]) :
      none()
  }
  var safe = fn => { try { return right(fn()) } catch (e) { return left(e) } }

  var fetchFailed = () => { throw 'could not connect to the server' }
  var fetchSuccesful = () => [{ id: 1, name: 'Joan', age: 29, employeeId: 1 },
                              { id: 2, name: 'Rick', age: 25, employeeId: 2 }]

  var clientRepository = ({
    getById: (id) => {
      return safe(fetchSuccesful)
        .bind(response => response.filter(c => c.id == id)
          .safeHead()
          .toEither(`there is no client with id ${id}`))
    }

  });

  var employeeRepository = ({
    getById: (id) =>
      [{ id: 1, name: 'jim', age: 29 },
      { id: 2, name: 'jane', age: 25 }]
        .filter(employee => employee.id == id)
        .safeHead()
        .toEither(`there is no employee with id ${id}`)
  });

  var displayAssignedEmployeeForClientId = (clientId) =>
    clientRepository
      .getById(clientId)
      .bind(client => employeeRepository.getById(client.employeeId))
      .map(e => e.name)
      .cata({
        right: name => console.log("assigned Employee name: " + name),
        left: error => console.log("error: " + error)
      });

  displayAssignedEmployeeForClientId(1)