maybe-monade
Version:
Maybe monad implementation in Typescript
74 lines (73 loc) • 2.61 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var maybe_1 = require("./maybe");
var utils_1 = require("./utils");
var MaybeCallback = /** @class */ (function () {
function MaybeCallback(callback) {
this.callback = callback;
}
/**
* return an instance of Maybe wrapping an empty value
*/
MaybeCallback.none = function () {
return new MaybeCallback(null);
};
/**
* if the provided callback is not a function, return an instance of Maybe wrapping a nonempty value,
* otherwise throw an error
* @param callback
*/
MaybeCallback.some = function (callback) {
if (typeof callback !== "function") {
throw new Error(utils_1.ErrorMessages.emptyCallback);
}
return new MaybeCallback(callback);
};
/**
* return true if the wrapped value is empty, false otherwise
*/
MaybeCallback.prototype.isEmpty = function () {
return this.callback === null;
};
/**
* Call the wrapped function in unsafe mode (could throw errors)
* if the wrapped function is empty return empty Maybe,
* otherwise return an instance of Maybe wrapping the function result
* @param args : arguments to pass to the wrapped function
*/
MaybeCallback.prototype.apply = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (!this.isEmpty() && typeof this.callback === "function") {
return maybe_1.Maybe.fromValue(this.callback.apply(null, args));
}
else {
return maybe_1.Maybe.none();
}
};
/**
* call the wrapped function in a safe mode,
* wrap the execution in a try catch bloc. in case of error return empty Maybe,
* otherwise return an instance of Maybe wrapping the function result
* @param args : arguments to pass to the wrapped function
*/
MaybeCallback.prototype.applySafe = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (this.isEmpty() || typeof this.callback !== "function") {
return maybe_1.Maybe.none();
}
try {
return maybe_1.Maybe.fromValue(this.callback.apply(null, args));
}
catch (ex) {
return maybe_1.Maybe.none();
}
};
return MaybeCallback;
}());
exports.MaybeCallback = MaybeCallback;