Skip to content

Instantly share code, notes, and snippets.

@ryankinal
Created January 23, 2013 13:22
Show Gist options
  • Save ryankinal/4605531 to your computer and use it in GitHub Desktop.
Save ryankinal/4605531 to your computer and use it in GitHub Desktop.
Recursive-descent parser to find the second occurrence of the string 'ABC' in a string.
var aPosition = -1,
position = 0,
count = 0,
desiredCount = 2,
string = 'XYZ 123 ABC 456 ABC 789 ABC',
tokens = string.split('');
var parse = function(tokens)
{
if (tokens[0] === 'A')
{
return a(tokens);
}
else
{
tokens.shift();
position++;
return parse(tokens);
}
}
var a = function(tokens)
{
if (tokens[0] === 'A')
{
tokens.shift();
aPosition = position;
position++;
return b(tokens);
}
else
{
return parse(tokens);
}
}
var b = function(tokens)
{
if (tokens[0] === 'B')
{
tokens.shift();
position++;
return c(tokens);
}
else
{
return parse(tokens);
}
}
var c = function(tokens)
{
if (tokens[0] === 'C')
{
tokens.shift();
position++;
count++;
if (count === desiredCount)
{
return aPosition;
}
else
{
return parse(tokens);
}
}
else
{
return parse(tokens);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment