io-square
Version:
IO Monad library for JavaScript
108 lines (97 loc) • 3.47 kB
JavaScript
;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var IO = function () {
function IO(ioFunc) {
var _this = this;
_classCallCheck(this, IO);
this.then = function (cb) {
return ioFunc(function () {
if ((arguments.length <= 0 ? undefined : arguments[0]) instanceof Error) {
_this.err(arguments.length <= 0 ? undefined : arguments[0]);
} else {
cb.apply(undefined, arguments);
}
});
};
this.err = function (e) {
return console.log(e.message);
};
}
_createClass(IO, [{
key: "error",
value: function error(handler) {
this.err = handler;
return this;
}
}, {
key: "reject",
value: function reject(pred) {
var saveThen = this.then;
this.then = function (cb) {
saveThen(function () {
var result = pred.apply(undefined, arguments);
if (result !== null) {
if (Array.isArray(result)) {
cb.apply(undefined, _toConsumableArray(result));
} else {
cb(result);
}
}
});
};
return this;
}
}, {
key: "map",
value: function map(transform) {
var saveThen = this.then;
this.then = function (cb) {
saveThen(function () {
var result = transform.apply(undefined, arguments);
if (Array.isArray(result)) {
cb.apply(undefined, _toConsumableArray(result));
} else {
cb(result);
}
});
};
return this;
}
}, {
key: "bind",
value: function bind(ioFunc) {
var saveThen = this.then;
this.then = function (cb) {
saveThen(function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var io = ioFunc.apply(undefined, args);
io.then(function () {
for (var _len2 = arguments.length, ioargs = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
ioargs[_key2] = arguments[_key2];
}
return cb.apply(undefined, args.concat(ioargs));
});
});
};
return this;
}
}], [{
key: "timer",
value: function timer(s) {
var intervalId;
var timer = new IO(function (cb) {
intervalId = setInterval(cb, Math.floor(s * 1000));
});
timer.clear = function () {
return clearInterval(intervalId);
};
return timer;
}
}]);
return IO;
}();
module.exports = IO;