diff --git a/README.md b/README.md index bc26ff7..8239176 100644 --- a/README.md +++ b/README.md @@ -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*) diff --git a/index.js b/index.js index 10c4fc4..1bf8fb2 100755 --- a/index.js +++ b/index.js @@ -21,7 +21,10 @@ exports.none = Object.create({ return []; }, orElse: callOrReturn, - valueOrElse: callOrReturn + valueOrElse: callOrReturn, + matchWith: function(choices) { + return choices.None(); + } }); function callOrReturn(value) { @@ -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; }; diff --git a/test/options.test.js b/test/options.test.js index 3c6c8b3..448f582 100644 --- a/test/options.test.js +++ b/test/options.test.js @@ -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(); }; \ No newline at end of file