From c2eefda8f823958f3637079f41e783c4cbae9ffa Mon Sep 17 00:00:00 2001 From: Matt Basta Date: Thu, 6 Feb 2014 13:51:56 -0800 Subject: [PATCH] Add option to alphabetize object literals --- README.md | 3 +++ lib/compress.js | 24 +++++++++++++++++++++++- test/compress/objects.js | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 test/compress/objects.js diff --git a/README.md b/README.md index 27d06cd6..6d15eea1 100644 --- a/README.md +++ b/README.md @@ -256,6 +256,9 @@ to set `true`; it's effectively a shortcut for `foo=true`). - `drop_console` -- default `false`. Pass `true` to discard calls to `console.*` functions. +- `alphabetize` -- default `false`. Pass `true` to alphabetize keys in object + literals. + ### The `unsafe` option It enables some transformations that *might* break code logic in certain diff --git a/lib/compress.js b/lib/compress.js index 005c606d..b434206b 100644 --- a/lib/compress.js +++ b/lib/compress.js @@ -72,6 +72,7 @@ function Compressor(options, false_by_default) { screw_ie8 : false, drop_console : false, angular : false, + alphabetize : !false_by_default, warnings : true, global_defs : {} @@ -2365,7 +2366,28 @@ merge(Compressor.prototype, { return self; }; OPT(AST_Array, literals_in_boolean_context); - OPT(AST_Object, literals_in_boolean_context); OPT(AST_RegExp, literals_in_boolean_context); + OPT(AST_Object, function(self, compressor) { + if (compressor.option("alphabetize") && self.properties.length) { + var sortedProps = self.properties.sort(function(a, b) { + if (a.key < b.key) { + return -1; + } + if (a.key > b.key) { + return 1; + } + return 0; + }); + for (var i = self.properties.length; i--;) { + if (self.properties[i] !== sortedProps[i]) { + return make_node(AST_Object, self, { + properties: sortedProps + }); + } + } + } + + return literals_in_boolean_context(self, compressor); + }); })(); diff --git a/test/compress/objects.js b/test/compress/objects.js new file mode 100644 index 00000000..45eed8f4 --- /dev/null +++ b/test/compress/objects.js @@ -0,0 +1,35 @@ +alphabetize_disabled_by_default: { + options = {}; + input: { + foo({ + c: 1, + a: 2, + b: 3 + }); + } + expect: { + foo({ + c: 1, + a: 2, + b: 3 + }); + } +} + +alphabetize_orders_keys: { + options = { alphabetize: true }; + input: { + foo({ + c: 1, + a: 2, + b: 3 + }); + } + expect: { + foo({ + a: 2, + b: 3, + c: 1 + }); + } +}