all files / lib/data/ option.js

100% Statements 32/32
100% Branches 14/14
100% Functions 11/11
100% Lines 32/32
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77                      29726×     26188×     3538×     34147×     16788× 12798×   3990×                           1669× 244×   1425×       15678× 12640×   3038×              
/*
 * Parsec
 * https://github.com/d-plaindoux/parsec
 *
 * Copyright (c) 2016 Didier Plaindoux
 * Licensed under the LGPL2 license.
 */
 
module.exports = (function () {
    
    'use strict';
 
    function Option(value) {
        this.value = value;
    }    
    
    function someOrNone(value) {
        return new Option(value);
    }
    
    function none() {
        return new Option();
    }
    
    Option.prototype.isPresent = function () {
        return (this.value !== null && this.value !== undefined);
    };
    
    Option.prototype.map = function (bindCall) {
        if (this.isPresent()) {
            return someOrNone(bindCall(this.value));
        } else {
            return this;
        }
    };
 
    Option.prototype.flatmap = function (bindCall) {
        if (this.isPresent()) {
            return bindCall(this.value);
        } else {
            return this;
        }
    };
 
    Option.prototype.filter = function (f) {
        if (this.isPresent() && f(this.value)) {
            return this;
        }
        
        return none();
    };
    
    Option.prototype.get = function () {
        return this.value;
    };
    
    Option.prototype.orElse = function (value) {
        if (this.isPresent()) {
            return this.value;
        } else {
            return value;
        }
    };
    
    Option.prototype.orLazyElse = function (value) {
        if (this.isPresent()) {
            return this.value;
        } else {
            return value();
        }
    };
    
    return {
        some  : someOrNone,
        none  : none
    };
}());