Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,13 @@ If `other` is not a function:
* `some(value).valueOrElse(other)` returns `value`
* `none.valueOrElse(other)` returns `other`

### matchWith(*choices*)

`choices` is an object of shape `{ Some: function, None: function }`.

* `some(value).matchWith({ Some: funcA, None: funcB })` returns the result of `funcA(value)`
* `none.matchWith({ Some: funcA, None: funcB })` returns the result of `funcB()`

## Functions

### option.isOption(*value*)
Expand Down
9 changes: 8 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@ exports.none = Object.create({
return [];
},
orElse: callOrReturn,
valueOrElse: callOrReturn
valueOrElse: callOrReturn,
matchWith: function(choices) {
return choices.None();
}
});

function callOrReturn(value) {
Expand Down Expand Up @@ -76,6 +79,10 @@ Some.prototype.valueOrElse = function(value) {
return this._value;
};

Some.prototype.matchWith = function(choices) {
return choices.Some(this._value);
};

exports.isOption = function(value) {
return value === exports.none || value instanceof Some;
};
Expand Down
16 changes: 16 additions & 0 deletions test/options.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -171,4 +171,20 @@ exports["when predicate(value) is false, some(value).filter(predicate) returns n

test.deepEqual(some11.filter(equals3), options.none);
test.done();
};

exports.noneMatchWithCallsFunctionUnderNoneKey = function(test) {
test.deepEqual(4, options.none.matchWith({
None: function() { return 4; },
Some: function(value) { return value; }
}));
test.done();
};

exports.someMatchWithCallsFunctionUnderSomeKeyPassingTheValue = function(test) {
test.deepEqual(12, options.some(11).matchWith({
None: function() { return 4; },
Some: function(value) { return value + 1 }
}));
test.done();
};