Skip to content

Commit fa68c63

Browse files
Improve YAML parser performance per code review
- Extract regex patterns outside loop for better performance - Add helper function ensureArray() to reduce code duplication - Use pre-compiled regex patterns throughout parser Co-authored-by: aarongustafson <[email protected]>
1 parent 2479e3e commit fa68c63

File tree

1 file changed

+17
-6
lines changed

1 file changed

+17
-6
lines changed

scripts/utils/frontmatter.mjs

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,20 @@ function parseYaml(yamlText) {
5353
let inMultilineString = false;
5454
let multilineValue = '';
5555

56+
// Pre-compile regex patterns for better performance
57+
const indentedPropertyRegex = /^\s+\w+:/;
58+
const objectPropertyRegex = /^(\w+):\s*(.+)$/;
59+
60+
/**
61+
* Initialize array for current key if not already initialized
62+
*/
63+
const ensureArray = () => {
64+
if (currentKey && !currentArray) {
65+
result[currentKey] = [];
66+
currentArray = result[currentKey];
67+
}
68+
};
69+
5670
for (let line of lines) {
5771
const originalLine = line;
5872
const trimmedLine = line.trim();
@@ -77,7 +91,7 @@ function parseYaml(yamlText) {
7791
}
7892

7993
// Handle object properties within arrays (indented with spaces, not starting with -)
80-
if (originalLine.match(/^\s+\w+:/) && !trimmedLine.startsWith('-') && currentObject) {
94+
if (indentedPropertyRegex.test(originalLine) && !trimmedLine.startsWith('-') && currentObject) {
8195
const colonIndex = trimmedLine.indexOf(':');
8296
if (colonIndex > 0) {
8397
const key = trimmedLine.substring(0, colonIndex).trim();
@@ -95,14 +109,11 @@ function parseYaml(yamlText) {
95109
const value = line.substring(2).trim();
96110

97111
// Initialize array if we have a currentKey but no array yet
98-
if (currentKey && !currentArray) {
99-
result[currentKey] = [];
100-
currentArray = result[currentKey];
101-
}
112+
ensureArray();
102113

103114
// Check if this is an object in an array (like related links)
104115
if (value.includes(':')) {
105-
const objMatch = value.match(/^(\w+):\s*(.+)$/);
116+
const objMatch = objectPropertyRegex.exec(value);
106117
if (objMatch) {
107118
const [, key, objValue] = objMatch;
108119
// Create a new object for this array item

0 commit comments

Comments
 (0)