UNPKG

@beenotung/tslib

Version:
60 lines (59 loc) 1.7 kB
"use strict"; /** * monad factory * reference : https://github.com/douglascrockford/monad/blob/master/monad.js * */ Object.defineProperty(exports, "__esModule", { value: true }); exports.createUnit = createUnit; const array_1 = require("../array"); function createUnit(modifier) { const prototype = Object.create(null); prototype.is_monad = true; const unit = Object.assign(function unit(value) { return unitFunction(value); }); function unitFunction(value) { const bind = (f, args) => f.call(void 0, value, ...(0, array_1.toArray)(args || [])); const map = (f, args) => bind((a, args) => unit(f.call(void 0, a, ...args)), args); const monad = { is_monad: true, bind, map, }; if (typeof modifier === 'function') { value = modifier(monad, value); } return monad; } const method = (name, f) => { prototype[name] = f; return unit; }; const lift_value = (name, f) => { prototype[name] = function () { const monad = this; return monad.bind(f, arguments); }; return unit; }; const lift = (name, f) => { prototype[name] = function () { const monad = this; return monad.bind((a, args) => { const b = f(a, ...args); if (b.is_monad) { return b; } else { return unit(b); } }, arguments); }; return unit; }; return Object.assign(unit, { method, lift_value, lift, }); }