UNPKG

1.95 kBJavaScriptView Raw
1"use strict";
2/**
3 * monad factory
4 * reference : https://github.com/douglascrockford/monad/blob/master/monad.js
5 * */
6Object.defineProperty(exports, "__esModule", { value: true });
7exports.createUnit = void 0;
8const array_1 = require("../array");
9function createUnit(modifier) {
10 const prototype = Object.create(null);
11 prototype.is_monad = true;
12 const unit = Object.assign(function unit(value) {
13 return unitFunction(value);
14 });
15 function unitFunction(value) {
16 const bind = (f, args) => f.call(void 0, value, ...array_1.toArray(args || []));
17 const map = (f, args) => bind((a, args) => unit(f.call(void 0, a, ...args)), args);
18 const monad = {
19 is_monad: true,
20 bind,
21 map,
22 };
23 if (typeof modifier === 'function') {
24 value = modifier(monad, value);
25 }
26 return monad;
27 }
28 const method = (name, f) => {
29 prototype[name] = f;
30 return unit;
31 };
32 const lift_value = (name, f) => {
33 prototype[name] = function () {
34 /* tslint:disable:no-invalid-this */
35 const monad = this;
36 /* tslint:enable:no-invalid-this */
37 return monad.bind(f, arguments);
38 };
39 return unit;
40 };
41 const lift = (name, f) => {
42 prototype[name] = function () {
43 /* tslint:disable:no-invalid-this */
44 const monad = this;
45 /* tslint:enable:no-invalid-this */
46 return monad.bind((a, args) => {
47 const b = f(a, ...args);
48 if (b.is_monad) {
49 return b;
50 }
51 else {
52 return unit(b);
53 }
54 }, arguments);
55 };
56 return unit;
57 };
58 return Object.assign(unit, {
59 method,
60 lift_value,
61 lift,
62 });
63}
64exports.createUnit = createUnit;
65//# sourceMappingURL=monad.js.map
\No newline at end of file