Guest User

Untitled

a guest
May 27th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. /*
  2. Path parser by Devon Govett
  3. Input: String path
  4. Returns: Array of objects with command and arguments
  5. */
  6.  
  7. //Number of allowed parameters for each command
  8. var parameters = {
  9. A: 7,
  10. a: 7,
  11. C: 6,
  12. c: 6,
  13. H: 1,
  14. h: 1,
  15. L: 2,
  16. l: 2,
  17. M: 2,
  18. m: 2,
  19. Q: 4,
  20. q: 4,
  21. S: 4,
  22. s: 4,
  23. T: 2,
  24. t: 2,
  25. V: 1,
  26. v: 1,
  27. Z: 0,
  28. z: 0
  29. };
  30.  
  31. /* PARSE THE PATH */
  32. var ret = [], cmd, args = [], curArg = "", found_decimal = false, undefined;
  33. for(var i = 0, len = path.length; i < len; i++) {
  34. var c = path[i];
  35. if(parameters[c] != undefined) {
  36. if(cmd) { //Save existing command
  37. if(curArg.length > 0) args[args.length] = +curArg;
  38. ret[ret.length] = { command: cmd, args: args };
  39. args = [], curArg = "", found_decimal = false;
  40. }
  41. cmd = c;
  42. }
  43. else if(c == " " || c == "," || (c == "-" && curArg.length > 0) || (c == "." && found_decimal)) {
  44. if(curArg.length == 0) continue;
  45.  
  46. if(args.length == parameters[cmd]) { //Handle reused commands
  47. ret[ret.length] = { command: cmd, args: args };
  48. args = [+curArg];
  49.  
  50. //handle assumed commands
  51. if(cmd == "M") cmd = "L";
  52. else if(cmd == "m") cmd = "l";
  53. }
  54. else {
  55. args[args.length] = +curArg;
  56. }
  57.  
  58. found_decimal = (c == ".");
  59. curArg = (c == "-" ? "-" : c == "." ? "." : ""); //fix for negative numbers or repeated decimals with no delimeter between commands
  60. }
  61. else {
  62. curArg += c;
  63. if(c == ".") found_decimal = true; //cache instead of using indexOf
  64. }
  65. }
  66. //Add the last command
  67. if(curArg.length > 0) args[args.length] = +curArg;
  68. ret[ret.length] = { command: cmd, args: args };
Add Comment
Please, Sign In to add comment