Slight optimization to `trimWhitespace`. Fix bug with `removeEmptyElements` cutting...
authorJuriy Zaytsev <kangax@gmail.com>
Mon, 1 Mar 2010 16:35:30 +0000 (11:35 -0500)
committerJuriy Zaytsev <kangax@gmail.com>
Mon, 1 Mar 2010 16:35:30 +0000 (11:35 -0500)
src/htmlminifier.js
tests/index.html

index 2276f80..d1c0f7b 100644 (file)
   }
   
   function trimWhitespace(str) {
-    return (str.trim ? str.trim() : str.replace(/^\s+/, '').replace(/\s+$/, ''));
+    return str.replace(/^\s+/, '').replace(/\s+$/, '');
+  }
+  if (String.prototype.trim) {
+    trimWhitespace = function(str) {
+      return str.trim();
+    };
   }
   
   function collapseWhitespace(str) {
         
         tag = tag.toLowerCase();
         currentTag = tag;
+        currentChars = '';
         
         buffer.push('<', tag);
         
       },
       end: function( tag ) {
         var isElementEmpty = currentChars === '' && tag === currentTag;
-        if ((options.removeEmptyElements && isElementEmpty && canRemoveElement(tag)) ||
-            (options.removeOptionalTags && isOptionalTag(tag))) {
-          // noop
+        if ((options.removeEmptyElements && isElementEmpty && canRemoveElement(tag))) {
+          // remove last "element" from buffer, return
+          buffer.splice(buffer.lastIndexOf('<'));
+          return;
+        }
+        else if (options.removeOptionalTags && isOptionalTag(tag)) {
+          // noop, leave start tag in buffer
         }
         else {
+          // push end tag to buffer
           buffer.push('</', tag.toLowerCase(), '>');
           results.push.apply(results, buffer);
         }
+        // flush buffer
         buffer.length = 0;
         currentChars = '';
       },
index ed95793..9cf97eb 100644 (file)
         });
         
         test('removing empty elements', function() {
+          
           equals(minify('<p>x</p>', { removeEmptyElements: true }), '<p>x</p>');
           equals(minify('<p></p>', { removeEmptyElements: true }), '');
           
           input = '<div>hello<span>world</span></div>';
           output = '<div>hello<span>world</span></div>';
           equals(minify(input, { removeEmptyElements: true }), output);
+          
+          input = '<p>x<span title="<" class="blah-moo"></span></p>';
+          output = '<p>x</p>';
+          equals(minify(input, { removeEmptyElements: true }), output);
+          
+          input = '<div>x<div>y <div>blah</div><div></div>foo</div>z</div>';
+          output = '<div>x<div>y <div>blah</div>foo</div>z</div>';
+          equals(minify(input, { removeEmptyElements: true }), output);
+          
+          input = '<img src="">';
+          equals(minify(input, { removeEmptyElements: true }), input);
+          
+          input = '<p><!-- x --></p>';
+          output = '';
+          equals(minify(input, { removeEmptyElements: true }), output);
         });
         
         test('collapsing boolean attributes', function(){