pattern-match
Advanced tools
Comparing version 0.1.0 to 0.2.0
@@ -312,2 +312,37 @@ var global = this; | ||
function Some(patterns) { | ||
this.patterns = patterns; | ||
} | ||
Some.prototype = Object.create(Pattern.prototype); | ||
Some.prototype.match = function(actual, matches) { | ||
// Try each pattern in its own temporary scratch sub-match object. | ||
var temp; | ||
for (var i = 0, n = this.patterns.length; i < n; i++) { | ||
temp = {}; | ||
try { | ||
matchPattern(this.patterns[i], actual, temp); | ||
// On success, commit the successful sub-matches to the real sub-match object. | ||
for (var key in temp) { | ||
if (!hasOwn.call(temp, key)) | ||
continue; | ||
matches[key] = temp[key]; | ||
} | ||
return; | ||
} catch (e) { | ||
if (!(e instanceof MatchError)) | ||
throw e; | ||
} | ||
} | ||
throw new MatchError("no alternates matched", actual, this); | ||
}; | ||
match.some = function() { | ||
return new Some(arguments); | ||
}; | ||
match.one = function(actual, pattern, template, thisArg) { | ||
@@ -314,0 +349,0 @@ return match(actual, function(when) { |
@@ -5,3 +5,3 @@ { | ||
"main": "lib/match.js", | ||
"version": "0.1.0", | ||
"version": "0.2.0", | ||
"engines": { | ||
@@ -8,0 +8,0 @@ "node": ">=0.8.6" |
@@ -161,2 +161,4 @@ ## pattern-match | ||
* **match.var(name[, pattern])** - matches the `pattern` (defaults to `any`) and saves the value in the sub-match object with property name `name`. | ||
* **match.all(pattern, ...)** - matches if every `pattern` matches. | ||
* **match.some(pattern, ...)** - matches if one `pattern` matches. | ||
* **pred(testValue)** - matches any value for which `pred` returns a truthy value. | ||
@@ -163,0 +165,0 @@ * **{ x1: pattern1, ..., xn: patternn }** - matches any object with property names `x1` to `xn` matching patterns `pattern1` to `patternn`, respectively. Only the own properties of the pattern are used. |
@@ -196,5 +196,32 @@ var match = require('../lib/match'); | ||
100)); | ||
match().when(match.all()); | ||
}); | ||
test.throws(function() { | ||
match(100).when(match.all(match.number, | ||
match.integer, | ||
match.range(0, 1000), | ||
match.string)); | ||
}); | ||
}); | ||
exports.testSome = sync(function(test) { | ||
test.doesNotThrow(function() { | ||
match("hello").when(match.some(match.string, | ||
match.number, | ||
match.boolean)); | ||
match(100).when(match.some(match.string, | ||
match.number, | ||
match.boolean)); | ||
match(true).when(match.some(match.string, | ||
match.number, | ||
match.boolean)); | ||
}); | ||
test.throws(function() { | ||
match({}).when(match.some(match.string, | ||
match.number, | ||
match.boolean)); | ||
match().when(match.some()); | ||
}); | ||
}); | ||
var MAX_INTEGER = 9007199254740991; | ||
@@ -201,0 +228,0 @@ |
32598
594
178