Skip to content

Instantly share code, notes, and snippets.

@devongovett
Created June 3, 2010 20:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devongovett/424444 to your computer and use it in GitHub Desktop.
Save devongovett/424444 to your computer and use it in GitHub Desktop.
/*
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