Created
January 23, 2013 13:22
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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