Skip to content

Commit

Permalink
parseAssertion: Simplify, get rid of a helper function.
Browse files Browse the repository at this point in the history
  • Loading branch information
papandreou committed Mar 7, 2017
1 parent 30d7e50 commit 1c908b3
Showing 1 changed file with 12 additions and 22 deletions.
34 changes: 12 additions & 22 deletions lib/Unexpected.js
Original file line number Diff line number Diff line change
Expand Up @@ -357,31 +357,21 @@ Unexpected.prototype.parseAssertion = function (assertionString) {
var tokens = [];
var nextIndex = 0;

function lookupType(typeName) {
// Pull out into a method so it can fall back to that.parent.lookupType?
var instance = that;
var result;
while (instance && !result) {
result = instance.typeByName[typeName];
instance = instance.parent;
}
if (!result) {
throw new Error('Unknown type: ' + typeName + ' in ' + assertionString);
}
return result;
}

function parseType(assertionString) {
return assertionString.split('|').map(function (type) {
var matchNameAndOperator = type.match(/^([a-z_](?:|[a-z0-9_.-]*[_a-z0-9]))([+*?]|)$/i);
function parseTypeToken(typeToken) {
return typeToken.split('|').map(function (typeDeclaration) {
var matchNameAndOperator = typeDeclaration.match(/^([a-z_](?:|[a-z0-9_.-]*[_a-z0-9]))([+*?]|)$/i);
if (!matchNameAndOperator) {
throw new SyntaxError('Cannot parse type declaration:' + type);
throw new SyntaxError('Cannot parse type declaration:' + typeDeclaration);
}
var type = that.getType(matchNameAndOperator[1]);
if (!type) {
throw new Error('Unknown type: ' + matchNameAndOperator[1] + ' in ' + assertionString);
}
var operator = matchNameAndOperator[2];
return {
minimum: !operator || operator === '+' ? 1 : 0,
maximum: operator === '*' || operator === '+' ? Infinity : 1,
type: lookupType(matchNameAndOperator[1])
type: type
};
});
}
Expand All @@ -396,7 +386,7 @@ Unexpected.prototype.parseAssertion = function (assertionString) {
throw new SyntaxError('Cannot parse token at index ' + nextIndex + ' in ' + assertionString);
}
if ($1) {
tokens.push(parseType($1));
tokens.push(parseTypeToken($1));
} else {
tokens.push($2.trim());
}
Expand All @@ -406,9 +396,9 @@ Unexpected.prototype.parseAssertion = function (assertionString) {
var assertion;
if (tokens.length === 1 && typeof tokens[0] === 'string') {
assertion = {
subject: parseType('any'),
subject: parseTypeToken('any'),
assertion: tokens[0],
args: [parseType('any*')]
args: [parseTypeToken('any*')]
};
} else {
assertion = {
Expand Down

0 comments on commit 1c908b3

Please sign in to comment.