4.5 Extending Promise to Functor

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)),
    matchWith: pattern => pattern.some(v),
  });
  var none = () => ({
    map: (f) => none(),
    matchWith: pattern => pattern.none(v),
  });

  Array.prototype.firstOrNone = function (predicate) {
    var result = this.find(predicate);
    if (result)
      return some(result)
    else
      return none()
  }
  var fetchClientsMock = () =>
    [{ id: 1, name: 'jim', age: 29 },
    { id: 2, name: 'jane', age: 25 }]


  var clientRepository = ({
    getById: (id) => fetchClientsMock().firstOrNone(c => c.id == id)
  });

  clientRepository.getById(1)
    .map(client => client.name)
    .matchWith({
      some: value => console.log(`the client name is ${value}`),
      none: () => console.log(`there is no client with that id `)
    })