Created
June 3, 2010 20:38
-
-
Save devongovett/424444 to your computer and use it in GitHub Desktop.
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
/* | |
Path parser by Devon Govett | |
Input: String path | |
Returns: Array of objects with command and arguments | |
*/ | |
//Number of allowed parameters for each command | |
var parameters = { | |
A: 7, | |
a: 7, | |
C: 6, | |
c: 6, | |
H: 1, | |
h: 1, | |
L: 2, | |
l: 2, | |
M: 2, | |
m: 2, | |
Q: 4, | |
q: 4, | |
S: 4, | |
s: 4, | |
T: 2, | |
t: 2, | |
V: 1, | |
v: 1, | |
Z: 0, | |
z: 0 | |
}; | |
/* PARSE THE PATH */ | |
var ret = [], cmd, args = [], curArg = "", found_decimal = false, undefined; | |
for(var i = 0, len = path.length; i < len; i++) { | |
var c = path[i]; | |
if(parameters[c] != undefined) { | |
if(cmd) { //Save existing command | |
if(curArg.length > 0) args[args.length] = +curArg; | |
ret[ret.length] = { command: cmd, args: args }; | |
args = [], curArg = "", found_decimal = false; | |
} | |
cmd = c; | |
} | |
else if(c == " " || c == "," || (c == "-" && curArg.length > 0) || (c == "." && found_decimal)) { | |
if(curArg.length == 0) continue; | |
if(args.length == parameters[cmd]) { //Handle reused commands | |
ret[ret.length] = { command: cmd, args: args }; | |
args = [+curArg]; | |
//handle assumed commands | |
if(cmd == "M") cmd = "L"; | |
else if(cmd == "m") cmd = "l"; | |
} | |
else { | |
args[args.length] = +curArg; | |
} | |
found_decimal = (c == "."); | |
curArg = (c == "-" ? "-" : c == "." ? "." : ""); //fix for negative numbers or repeated decimals with no delimeter between commands | |
} | |
else { | |
curArg += c; | |
if(c == ".") found_decimal = true; //cache instead of using indexOf | |
} | |
} | |
//Add the last command | |
if(curArg.length > 0) args[args.length] = +curArg; | |
ret[ret.length] = { command: cmd, args: args }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment