Skip to content

Commit

Permalink
fix: improve the performance of replacing returns with enclosing whit…
Browse files Browse the repository at this point in the history
…espaces
  • Loading branch information
josdejong committed Nov 9, 2021
1 parent cbfde09 commit de05b10
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
8 changes: 6 additions & 2 deletions src/lib/utils/domUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ export function traverseInnerText(element, buffer) {
// text node
if (element.nodeValue) {
// remove return characters and the whitespaces surrounding those return characters
const trimmedValue = element.nodeValue.replace(regexReturnAndSurroundingWhitespace, '')
const trimmedValue = removeReturnsAndSurroundingWhitespace(element.nodeValue)
if (trimmedValue !== '') {
return buffer.flush() + trimmedValue
} else {
Expand Down Expand Up @@ -160,7 +160,11 @@ export function traverseInnerText(element, buffer) {

// regular expression matching one or multiple return characters with all their
// enclosing white spaces
export const regexReturnAndSurroundingWhitespace = /(\b|^)\s*\n\s*(\b|$)/g
export function removeReturnsAndSurroundingWhitespace(text) {
return text.replace(/(\b|^)\s*(\b|$)/g, (match) => {
return /\n/.exec(match) ? '' : match
})
}

export function isChildOfNodeName(element, nodeName) {
return isChildOf(element, (e) => e.nodeName.toUpperCase() === nodeName.toUpperCase())
Expand Down
6 changes: 3 additions & 3 deletions src/lib/utils/domUtils.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import assert from 'assert'
import { escapeHTML, regexReturnAndSurroundingWhitespace, unescapeHTML } from './domUtils.js'
import { escapeHTML, removeReturnsAndSurroundingWhitespace, unescapeHTML } from './domUtils.js'

describe('domUtils', () => {
it('escapeHTML', () => {
Expand All @@ -22,8 +22,8 @@ describe('domUtils', () => {

it('regex should match whitespace and surrounding whitespace', () => {
assert.strictEqual(
'A\nB \nC \n D \n\n E F'.replace(regexReturnAndSurroundingWhitespace, '*'),
'A*B*C*D*E F'
removeReturnsAndSurroundingWhitespace(' \n A\nB \nC \n D \n\n E F\n '),
'ABCDE F'
)
})
})

0 comments on commit de05b10

Please sign in to comment.