|
| 1 | +function pathDataParser(data) { |
| 2 | + const commands = []; |
| 3 | + let currentCommand = null; |
| 4 | + let currentParams = []; |
| 5 | + let currentParam = ''; |
| 6 | + |
| 7 | + for (let i = 0; i < data.length; i++) { |
| 8 | + const char = data[i]; |
| 9 | + |
| 10 | + if (char === ' ' || char === ',') { |
| 11 | + if (currentParam !== '') { |
| 12 | + currentParams.push(parseFloat(currentParam)); |
| 13 | + currentParam = ''; |
| 14 | + } |
| 15 | + } else if (/[a-zA-Z]/.test(char)) { |
| 16 | + if (currentCommand !== null) { |
| 17 | + commands.push({ command: currentCommand, parameters: currentParams }); |
| 18 | + currentParams = []; |
| 19 | + } |
| 20 | + currentCommand = char; |
| 21 | + } else { |
| 22 | + currentParam += char; |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + if (currentCommand !== null) { |
| 27 | + if (currentParam !== '') { |
| 28 | + currentParams.push(parseFloat(currentParam)); |
| 29 | + } |
| 30 | + commands.push({ command: currentCommand, parameters: currentParams }); |
| 31 | + } |
| 32 | + |
| 33 | + return commands; |
| 34 | +} |
| 35 | + |
| 36 | +// Examples |
| 37 | +console.log(pathDataParser("")); |
| 38 | +console.log(pathDataParser("M 0 0")); |
| 39 | +console.log(pathDataParser("M 1 1.5 L 0 1.5 0 0.5 1 0.5 0.5 0 0 0.5 1 1.5 1 0.5 0 1.5")); |
| 40 | +console.log(pathDataParser("M 0,1 h 1 v -1 h 1 v 1 h 1 C 2,1 3,3 1.5,3 C 0,3 1,1 0,1 z")); |
0 commit comments