parser-combinator
Version:
Parser combinators
139 lines (125 loc) • 3.75 kB
JavaScript
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/*
* Parsec
* https://github.com/d-plaindoux/parsec
*
* Copyright (c) 2016 Didier Plaindoux
* Licensed under the LGPL2 license.
*/
var Try = function () {
function Try(value, error) {
_classCallCheck(this, Try);
this.value = value;
this.error = error;
}
_createClass(Try, [{
key: 'isSuccess',
value: function isSuccess() {
return this.error === null;
}
}, {
key: 'isFailure',
value: function isFailure() {
return !this.isSuccess();
}
}, {
key: 'onSuccess',
value: function onSuccess(bindCall) {
if (this.isSuccess()) {
bindCall(this.value);
}
return this;
}
}, {
key: 'onFailure',
value: function onFailure(bindCall) {
if (this.isFailure()) {
bindCall(this.error);
}
return this;
}
}, {
key: 'map',
value: function map(bindCall) {
if (this.isSuccess()) {
try {
return success(bindCall(this.value));
} catch (e) {
return failure(e);
}
} else {
return this;
}
}
}, {
key: 'flatmap',
value: function flatmap(bindCall) {
if (this.isSuccess()) {
try {
return bindCall(this.value);
} catch (e) {
return failure(e);
}
} else {
return this;
}
}
}, {
key: 'success',
value: function success() {
return this.value;
}
}, {
key: 'failure',
value: function failure() {
return this.error;
}
}, {
key: 'recoverWith',
value: function recoverWith(value) {
if (this.isSuccess()) {
return this.value;
} else {
return value;
}
}
}, {
key: 'lazyRecoverWith',
value: function lazyRecoverWith(value) {
if (this.isSuccess()) {
return this.value;
} else {
return value(this.error);
}
}
}, {
key: 'filter',
value: function filter(f) {
if (this.isSuccess()) {
if (f(this.value)) {
return this;
} else {
return failure(new Error('invalid filter'));
}
}
return this;
}
}]);
return Try;
}();
function success(value) {
return new Try(value, null);
}
function failure(error) {
return new Try(null, error);
}
exports.default = {
success: success,
failure: failure
};
//# sourceMappingURL=try.js.map