Skip to content

Commit

Permalink
Merge pull request #117 from tedious/newline_optimization
Browse files Browse the repository at this point in the history
Optimize newline and empty comment normalization
  • Loading branch information
tedivm authored Mar 4, 2023
2 parents fd12678 + 4e93449 commit a13582e
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
30 changes: 29 additions & 1 deletion src/JShrink/Minifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ protected function minifyDirectToOutput($js, $options)
protected function initialize($js, $options)
{
$this->options = array_merge(static::$defaultOptions, $options);
$this->input = str_replace(["\r\n", '/**/', "\r"], ["\n", "", "\n"], $js);
$this->input = $js;

// We add a newline to the end of the script to make it easier to deal
// with comments at the bottom of the script- this prevents the unclosed
Expand Down Expand Up @@ -308,6 +308,12 @@ protected function getChar()
$this->index++;
}

# Convert all line endings to unix standard.
# `\r\n` converts to `\n\n` and is minified.
if ($char == "\r") {
$char = "\n";
}

// Normalize all whitespace except for the newline character into a
// standard space.
if ($char !== "\n" && $char < "\x20") {
Expand All @@ -317,6 +323,19 @@ protected function getChar()
return $char;
}

/**
* This function returns the next character without moving the index forward.
*
*
* @return string The next character
* @throws \RuntimeException
*/
protected function peek()
{
# Pull the next character but don't push the index.
return $this->index < $this->len ? $this->input[$this->index] : false;
}

/**
* This function gets the next "real" character. It is essentially a wrapper
* around the getChar function that skips comments. This has significant
Expand Down Expand Up @@ -387,6 +406,15 @@ protected function processMultiLineComments($startIndex)
$this->getChar(); // current C
$thirdCommentString = $this->getChar();

// Detect a completely empty comment, ie `/**/`
if ($thirdCommentString == "*") {
$peekChar = $this->peek();
if ($peekChar == "/") {
$this->index++;
return;
}
}

// kill everything up to the next */ if it's there
if ($this->getNext('*/')) {
$this->getChar(); // get *
Expand Down
1 change: 1 addition & 0 deletions tests/Resources/jshrink/input/empty_comment_oneline.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/**/ var test /**/
1 change: 1 addition & 0 deletions tests/Resources/jshrink/output/empty_comment_oneline.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
var test

0 comments on commit a13582e

Please sign in to comment.