@@ -3,16 +3,34 @@ export const IS_NON_DIMENSIONAL = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine
3
3
4
4
const ENCODED_ENTITIES = / [ & < > " ] / ;
5
5
6
- export function encodeEntities ( input ) {
7
- const s = String ( input ) ;
8
- if ( ! ENCODED_ENTITIES . test ( s ) ) {
9
- return s ;
6
+ export function encodeEntities ( str ) {
7
+ // Ensure we're always parsing and returning a string:
8
+ str += '' ;
9
+
10
+ // Skip all work for strings with no entities needing encoding:
11
+ if ( ENCODED_ENTITIES . test ( str ) === false ) return str ;
12
+
13
+ let last = 0 ,
14
+ i = 0 ,
15
+ out = '' ,
16
+ ch = '' ;
17
+
18
+ // Seek forward in str until the next entity char:
19
+ for ( ; i < str . length ; i ++ ) {
20
+ switch ( str . charCodeAt ( i ) ) {
21
+ case 60 : ch = '<' ; break ;
22
+ case 62 : ch = '>' ; break ;
23
+ case 34 : ch = '"' ; break ;
24
+ case 38 : ch = '&' ; break ;
25
+ default : continue ;
26
+ }
27
+ // Append skipped/buffered characters and the encoded entity:
28
+ if ( i > last ) out += str . slice ( last , i ) ;
29
+ out += ch ;
30
+ // Start the next seek/buffer after the entity's offset:
31
+ last = i + 1 ;
10
32
}
11
- return s
12
- . replace ( / & / g, '&' )
13
- . replace ( / < / g, '<' )
14
- . replace ( / > / g, '>' )
15
- . replace ( / " / g, '"' ) ;
33
+ return out + str . slice ( last , i ) ;
16
34
}
17
35
18
36
export let indent = ( s , char ) =>
0 commit comments