Skip to content

Commit

Permalink
Minify: Collapse adjacent var/const declarations
Browse files Browse the repository at this point in the history
Variable and constant declarations like:

        var x=1;var y=2;

now becomes:

        var x=1,y=2;

and the same for const declarations. Interspersed var/const declarations
are not handled yet.
  • Loading branch information
erikd committed Aug 22, 2015
1 parent 95e650f commit c513b2c
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
5 changes: 5 additions & 0 deletions Tests/Minify.hs
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,11 @@ testMinifyProg = describe "Minify programs:" $ do
minifyProg "{a;;x;};y;z;;" `shouldBe` "a;x;y;z"
minifyProg "{b;;{x;y;};};z;;" `shouldBe` "b;x;y;z"

it "variable declaration" $ do
minifyProg " var a = 1 ; var b = 2 ;" `shouldBe` "var a=1,b=2"
minifyProg " var c=1;var d=2;var e=3;" `shouldBe` "var c=1,d=2,e=3"
minifyProg " const f = 1 ; const g = 2 ;" `shouldBe` "const f=1,g=2"
minifyProg " var h = 1 ; const i = 2 ;" `shouldBe` "var h=1;const i=2"

-- -----------------------------------------------------------------------------
-- Minify test helpers.
Expand Down
17 changes: 17 additions & 0 deletions src/Language/JavaScript/Process/Minify.hs
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,25 @@ fixStatementList =
fixList s [JSStatementBlock _ blk _ _] = fixList s blk
fixList s [x] = [fixStmtE s x]
fixList s (JSStatementBlock _ blk _ _:xs) = fixList semi (filter (not . isRedundant) blk) ++ fixList s xs
fixList s (JSConstant _ vs1 _:JSConstant _ vs2 _: xs) = fixList s (JSConstant spaceAnnot (concatCommaList vs1 vs2) s : xs)
fixList s (JSVariable _ vs1 _:JSVariable _ vs2 _: xs) = fixList s (JSVariable spaceAnnot (concatCommaList vs1 vs2) s : xs)
fixList s (x:xs) = fixStmtE semi x : fixList s xs

concatCommaList :: JSCommaList a -> JSCommaList a -> JSCommaList a
concatCommaList xs JSLNil = xs
concatCommaList JSLNil ys = ys
concatCommaList xs (JSLOne y) = JSLCons xs emptyAnnot y
concatCommaList xs ys =
let recurse (z, zs) = concatCommaList (JSLCons xs emptyAnnot z) zs
in maybe xs recurse $ headCommaList ys

headCommaList :: JSCommaList a -> Maybe (a, JSCommaList a)
headCommaList JSLNil = Nothing
headCommaList (JSLOne x) = Just (x, JSLNil)
headCommaList (JSLCons (JSLOne x) _ y) = Just (x, JSLOne y)
headCommaList (JSLCons xs _ y) =
let rebuild (x, ys) = (x, JSLCons ys emptyAnnot y)
in rebuild <$> headCommaList xs

-- -----------------------------------------------------------------------------
-- JSExpression and the rest can use the MinifyJS typeclass.
Expand Down

0 comments on commit c513b2c

Please sign in to comment.