Skip to content

Commit 6af3709

Browse files
authored
Refactor to improve performance w/ hoisted regex
Closes GH-39. Reviewed-by: Titus Wormer <[email protected]>
1 parent c8d5f67 commit 6af3709

File tree

2 files changed

+15
-4
lines changed

2 files changed

+15
-4
lines changed

lib/handle/comment.js

+11-3
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,12 @@
77

88
import {stringifyEntities} from 'stringify-entities'
99

10+
const htmlCommentRegex = /^>|^->|<!--|-->|--!>|<!-$/g
11+
12+
// Declare arrays as variables so it can be cached by `stringifyEntities`
13+
const bogusCommentEntitySubset = ['>']
14+
const commentEntitySubset = ['<', '>']
15+
1016
/**
1117
* Serialize a comment.
1218
*
@@ -27,10 +33,12 @@ export function comment(node, _1, _2, state) {
2733
? '<?' +
2834
stringifyEntities(
2935
node.value,
30-
Object.assign({}, state.settings.characterReferences, {subset: ['>']})
36+
Object.assign({}, state.settings.characterReferences, {
37+
subset: bogusCommentEntitySubset
38+
})
3139
) +
3240
'>'
33-
: '<!--' + node.value.replace(/^>|^->|<!--|-->|--!>|<!-$/g, encode) + '-->'
41+
: '<!--' + node.value.replace(htmlCommentRegex, encode) + '-->'
3442

3543
/**
3644
* @param {string} $0
@@ -39,7 +47,7 @@ export function comment(node, _1, _2, state) {
3947
return stringifyEntities(
4048
$0,
4149
Object.assign({}, state.settings.characterReferences, {
42-
subset: ['<', '>']
50+
subset: commentEntitySubset
4351
})
4452
)
4553
}

lib/handle/text.js

+4-1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@
99

1010
import {stringifyEntities} from 'stringify-entities'
1111

12+
// Declare array as variable so it can be cached by `stringifyEntities`
13+
const textEntitySubset = ['<', '&']
14+
1215
/**
1316
* Serialize a text node.
1417
*
@@ -32,7 +35,7 @@ export function text(node, _, parent, state) {
3235
: stringifyEntities(
3336
node.value,
3437
Object.assign({}, state.settings.characterReferences, {
35-
subset: ['<', '&']
38+
subset: textEntitySubset
3639
})
3740
)
3841
}

0 commit comments

Comments
 (0)