Coverage

100%
45
45
0

computation.js

100%
45
45
0
LineHitsSource
1// A computation describes a way to compute a value out of the environment.
2// The value may not immediately be available (eg. if it's being asynchronously
3// fetched from a server).
41var Computation = (function () {
5 function Computation(fn) {
614 this.fn = fn;
7 }
8 // Convenience functions to create pure and failing computations.
91 Computation.pure = function (value) {
102 return new Computation(function () {
1110 return value;
12 });
13 };
141 Computation.fail = function (e) {
152 return new Computation(function () {
165 throw e;
17 });
18 };
19
20 // Like the ES6 Promise#then function.
211 Computation.prototype.then = function (resolve, reject) {
228 var _this = this;
238 return new Computation(function () {
248 try {
258 return resolve(_this.fn());
26 } catch (e) {
274 if (reject) {
281 return reject(e);
29 } else {
303 throw e;
31 }
32 }
33 });
34 };
35
36 // Map over the result. Pending state and errors are passsed onto the next
37 // computation untounched.
381 Computation.prototype.fmap = function (f) {
395 return this.then(function (v) {
405 if (v === Computation.Pending) {
411 return Computation.Pending;
42 } else {
434 return f(v);
44 }
45 });
46 };
47
48 // Like fmap, but the function can return a computation which is then
49 // automatically executed.
501 Computation.prototype.bind = function (f) {
513 return this.fmap(function (v) {
523 return f(v).fn();
53 });
54 };
55
56 // Pending computations and errors are passed through.
571 Computation.liftA2 = function (a, b, f) {
583 try {
593 var av = a.fn(), bv = b.fn();
60
612 if (av !== Computation.Pending && bv !== Computation.Pending) {
621 return new Computation(function () {
631 return f(av, bv);
64 });
65 } else {
661 return Computation.pending;
67 }
68 } catch (e) {
691 return Computation.fail(e);
70 }
71 };
72
73 // Get the result of this computation. If the result is not available yet,
74 // return the fallback value.
751 Computation.prototype.get = function (fallback) {
7614 try {
7714 var result = this.fn();
789 if (result === Computation.Pending) {
793 return fallback;
80 } else {
816 return result;
82 }
83 } catch (e) {
845 return fallback;
85 }
86 };
871 Computation.Pending = {};
88
891 Computation.pending = new Computation(function () {
904 return Computation.Pending;
91 });
921 return Computation;
93})();
94
951if (typeof module !== 'undefined') {
961 module.exports = Computation;
97}
98