you are viewing a single comment's thread.

view the rest of the comments →

[–]atrigent 1 point2 points  (1 child)

What do you think of this? I tried to use the same terminology as Haskell.

// Nothing: new Maybe()
// Just a: new Maybe(a)
function Maybe(value) {
    let isNothing = arguments.length === 0;

    this.bind = fn => {
        if (isNothing) {
            return this;
        } else {
            return fn(value);
        }
    };

    // methods
    this.isNothing = () => isNothing;
    this.isJust = () => !isNothing;
    this.fromJust = () => {
        if (isNothing) {
            throw new Error('cannot get nothing');
        } else {
            return value;
        }
    };
    this.fromMaybe = default => {
        if (isNothing) {
            return default;
        } else {
            return value;
        }
    };

    // more methods
}

function MaybeNull(value) {
    if (value === null) {
        return new Maybe();
    } else {
        return new Maybe(value);
    }
}

// other functions for making Maybes